模板类中的模板函数的类型相同

时间:2013-01-01 01:15:49

标签: c++ templates function-templates class-template

我有以下代码:

#include <iostream>
using namespace std;

template<typename T> class myclass {
public:
    T data;

    myclass(T const & _data = T()) : data(_data) {}

    template<typename U> myclass<T> & operator=(myclass<U> const & rhs) {
        cout << data << " = " << rhs.data << endl;
        return *this;
    }
};

int main() {
    myclass<double> first(1);
    myclass<float> second(2);
    myclass<double> third(3);
    first=second;
    first=third;
}

现在,尽管编译完美,但输出仅为:

1 + 2

为什么不是第一个=第三个调用

myclass<double> & operator=(myclass<double> const & rhs)

2 个答案:

答案 0 :(得分:1)

复制赋值运算符绝不是函数模板。由于该类未声明复制赋值运算符,因此编译器会生成一个并使用此生成的运算符。如果添加这样的运算符,您将看到赋值:

myclass<T>& operator= (myclass<T> const& rhs) {
    std::cout << "(copy) " << data << " = " << rhs.data << '\n';
    return *this;
}

答案 1 :(得分:0)

复制赋值运算符绝不是模板。由于您没有定义一个,因此为您定义了默认版本(不会打印任何内容)。

相关问题