编辑更新代码:
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 anyNumbersCopy = anyNumbers;
return 0;
}
印刷:
“移动 ctor”
为什么会这样?
有没有办法强制调用默认的复制构造函数而不是模板化的 const& 构造函数?
如果可能的话,我想避免使模板构造函数显式,以便我仍然可以像这样隐式构造类;
Any number = 5;