构造函数和复制构造函数将如何查找这个可变参数模板类?
struct A {};
struct B {};
template < typename Head,
typename... Tail>
struct X : public Head,
public Tail...
{
X(int _i) : i(_i) { }
// add copy constructor
int i;
};
template < typename Head >
struct X<Head> { };
int main(int argc, const char *argv[])
{
X<A, B> x(5);
X<A, B> y(x);
// This must not be leagal!
// X<B, A> z(x);
return 0;
}
最佳答案
template < typename Head,
typename... Tail>
struct X : public Head,
public Tail...
{
X(int _i) : i(_i) { }
// add copy constructor
X(const X& other) : i(other.i) {}
int i;
};
在模板类中,X
作为类型意味着 X<Head, Tail...>
, 和所有 X
具有不同模板参数的是不同的类型,因此 X<A,B>
的复制构造函数不匹配 X<B,A>
.
关于c++ - 可变模板类中的(简单)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770127/