模板 class 模板构造函数的专业化
template class specialization at template constructor
是否可以为模板 class 的特定特化指定模板构造函数 仅 ?
我有这个代码:
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;
}
现在对于标准函数类型,由于第二个参数,您的构造函数无法专门化。
是否可以为模板 class 的特定特化指定模板构造函数 仅 ? 我有这个代码:
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;
}
现在对于标准函数类型,由于第二个参数,您的构造函数无法专门化。