【发布时间】:2015-10-27 08:52:57
【问题描述】:
我想根据模板参数值选择成员函数(复制构造函数)的实现。我想有两种方法:SFINAE 和模板偏特化。
最后一个应该是这样的:
#include <iostream>
template<typename A, bool sw>
struct B
{
B() {}
B(const B &b);
};
template<typename A>
B<A, false>::B(const B<A, false> &b)
{
std::cout << "false\n";
}
template<typename A>
B<A, true>::B(const B<A, true> &b)
{
std::cout << "true\n";
}
int main()
{
}
无法编译:nested name specifier 'B<A, false>::' for declaration does not refer into a class, class template or class template partial specialization。
SFINAE 方法也失败了:
#include <type_traits>
#include <iostream>
template<typename A, bool sw>
struct B
{
B() {}
template<typename U = typename std::enable_if<sw, B>::type>
B(const U &b)
{
std::cout << "true\n";
}
template<typename U = typename std::enable_if<!sw, B>::type>
B(const U &b)
{
std::cout << "false\n";
}
};
int main()
{
{
B<int, true> b;
auto bc = b; // cout << true
}
{
B<int, false> b;
auto bc = b; // cout << false
}
}
这里的编译错误是constructor cannot be redeclared和no type named 'type' in 'std::enable_if<false, B<int, false> >'; 'enable_if' cannot be used to disable this declaration。
有没有办法解决问题或者根据模板参数选择合适的复制构造函数?
【问题讨论】:
-
你不能只对一个类(或结构)的成员进行部分特化,你需要对整个类进行部分特化。
-
作为记录,这里的问题之一是您不能拥有模板化的复制构造函数(除了在您的情况下两个签名相同,这可以修复) ,因为隐式生成的复制构造函数总是在重载决议中获胜
标签: c++ templates c++11 sfinae