是否可以仅为其模板类的特定特化指定模板构造函数? 我有这段代码:
template <typename T>
class A {
public:
A(std::function<T()> f) : x(f) {}
template <typename Y>
A<void>(Y* x) : x(x) {}
private:
boost::variant<int*, char*, std::function<T()>> x;
}
我试图让第二个构造函数只针对非 std::function 参数进行编译,这就是为什么我试图找到一种方法来明确告诉编译器 T 在这种情况下应该为 void,但显然这赢了'编译。
最佳答案
您可以使用 SFINAE 和具有默认值的附加参数
template <typename T>
struct is_std_function : public std::false_type {};
template <typename T>
struct is_std_function<std::function<T> > : public std::true_type{};
template <typename T>
class A {
public:
A(std::function<T()> f) : x(f) {}
template <typename Y>
A(Y* x, typename std::enable_if< !is_std_function<Y>::value >::type * = 0) : x(x) {}
private:
boost::variant<int*, char*, std::function<T()>> x;
}
现在对于标准函数类型,由于第二个参数,您的构造函数无法特化。
关于c++ - 模板构造函数中的模板类特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173375/