修改更新的代码:
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&amp;构造
我想避免在可能的情况下使模板构造函数显式化,这样我仍然可以隐式构造这样的类;
Any number = 5;
答案 0 :(得分:5)
也许您的真实代码看起来更像这样?
class Any
{
public:
Any(){}
Any(const Any &other)
{
}
template<typename T>
Any(T &&other)
{
}
};
在这种情况下,模板更适合Any& other
(不是const
!)。然后解决方案是提供非const非模板复制构造函数重载:
class Any
{
public:
Any(){}
Any(const Any &other)
{
}
Any(Any &other)
{
}
template<typename T>
Any(T &&other)
{
}
};