【发布时间】:2016-07-28 23:16:14
【问题描述】:
采取以下,
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 淘汰吗?这是为了避免代码重复,因为有趣的是,似乎也没有办法使用委托构造函数(从复制构造函数委托给模板构造函数)。
【问题讨论】:
-
不,这不一样,它会呈现
f3(f2)一个错误,因为重载决议仍然选择复制构造函数并错误输出为deleted。 (我回复的评论是询问delete是否是一个选项)
标签: c++ templates c++11 constructor