我读到模板copy-con永远不是默认的onstructor,而模板赋值操作永远不是复制赋值操作符.
我无法理解为什么需要这个限制并立即上线到ideone并返回一个测试程序但是这里复制构造函数永远不会被调用进一步的谷歌搜索我遇到了模板化的构造函数并尝试了但仍然从未调用复制构造函数.
#include <iostream>
using namespace std;
template <typename T> class tt
{
public :
tt()
{
std::cout << std::endl << " CONSTRUCTOR" << std::endl;
}
template <typename U> const tt<T>& operator=(const tt<U>& that){std::cout << std::endl << " OPERATOR" << std::endl;}
template <typename U> tt(const tt<U>& that)
{
std::cout << std::endl << " COPY CONSTRUCTOR" << std::endl;
}
};
tt<int> test(void)
{
std::cout << std::endl << " INSIDE " << std::endl; tt<int> a; return a;
}
int main() …Run Code Online (Sandbox Code Playgroud) 我问过这个问题,关于使用模板版本重载复制构造函数和赋值运算符并考虑到涉及问题的混淆(因为它似乎是编译器错误),我想我只尝试使用模板复制构造函数和模板赋值运算符来走着瞧吧.但是编译器完全忽略了它们.
struct BaseClass
{
public:
BaseClass() {}
template<typename T>
BaseClass(const T& a_other)
{
int i = 0; // for break point which is not hit
}
template<typename T>
BaseClass& operator= (const T& a_other)
{
int i = 0; // for break point which is not hit
return *this;
}
};
struct MyClass : public BaseClass
{
};
int main()
{
MyClass i, j;
i = j;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能用模板版本覆盖默认值(我怀疑答案是默认值是更好的匹配,但我希望模板版本也可以作为默认值)?我能做些什么来确保调用模板版本而不是默认值?
编辑更新的代码:
class Any
{
public:
Any()
{
}
Any(const Any &other)
{
}
Any(Any &other) // added per Ben's answer
{
}
Any(Any &&other)
{
}
Any(const char *value)
{
}
template<typename T>
Any(const T &value)
{
}
template<typename T>
Any(T &&value)
{
cout << "move ctor" << endl;
}
template<typename T>
Any(const vector<T> &value)
{
}
template<typename T>
Any(vector<T> &&value)
{
}
};
int main(int argc, char *argv[])
{
vector<string> numbers;
numbers.push_back("one");
numbers.push_back("two");
numbers.push_back("three");
numbers.push_back("four");
Any anyNumbers(numbers);
Any …Run Code Online (Sandbox Code Playgroud)