先上代码
template <typename T>
class A
{
public:
A()
{
cout << "A()" << endl;
}
A(const A& a)
{
cout << "A(const A& a)" << endl;
}
template <typename U, typename... Args>
A(U & f, Args... arg)
{
cout << "A(U & f, Args... arg)" << endl;
}
};
int main()
{
A<int> a; //A()
A<int> b(a); //A(U & f, Args... arg)
return 0;
}
如果修改一下
template <typename U, typename... Args>
A(U f, Args... arg)
{
cout << "A(U & f, Args... arg)" << endl;
}
那么输出就变成了想要的方式了。
A()
A(const A& a)
为什么构造对象b的时候会调用A(U & f, Args... arg)
这个模板函数,而不是调用拷贝构造函数?
应该如何指定调用的构造函数?
巴扎黑2017-04-17 15:23:27
This should be related to the order in which C++ selects overloaded functions. For an actual parameter of type T, T& is preferred first, and then const T&.
So if you change the code to:
template <typename U, typename... Args>
A(const U& f, Args... arg)
{
cout << "A(const U & f, Args... arg)" << endl;
}
It will also execute A(const A& a)
first.