取以下
template<class T>
struct Foo {
Foo(){}
// a template constructor "generalized" over related types
template<class U>
Foo(Foo<U> const&) {
std::cout << 1;
}
// copy constructor
Foo(Foo const&) {
std::cout << 2;
}
};
及其用户:
void main() {
Foo<int> f1;
Foo<const int> f2(f1); // prints 1
Foo<const int> f3(f2); // prints 2
}
即使没有显式复制构造函数,编译器也会生成一个并将其用于f3(f2)
。
有没有办法强制模板过载?例如,复制构造函数可以是SFINAE输出的吗?这是为了避免代码重复,因为有趣的是,似乎也没有使用委派构造函数的方法(从复制构造函数委派到模板构造函数)。
构造函数模板永远不可能是复制构造函数,所以如果你不定义一个,编译器会隐式地为你做这件事,正如你已经发现的那样。
避免代码重复的一个解决方法是定义第三个构造函数,并从上面显示的两个构造函数中委托给它。
template<class T>
struct Foo {
Foo(){}
struct tag{};
// a template constructor "generalized" over related types
template<class U>
Foo(Foo<U> const& f)
: Foo(tag{}, f)
{
std::cout << 1 << 'n';
}
// copy constructor
Foo(Foo const& f)
: Foo(tag{}, f)
{
std::cout << 2 << 'n';
}
private:
template<class U>
Foo(tag, Foo<U> const&)
{
std::cout << 3 << 'n';
}
};
实时演示