C++ 模板构造函数上的模板类专门化

C++ 模板构造函数上的模板类专门化,c++,templates,specialization,boost-variant,C++,Templates,Specialization,Boost Variant,是否可以仅为模板类的特定专门化指定模板构造函数? 我有以下代码: 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<

是否可以仅为模板类的特定专门化指定模板构造函数? 我有以下代码:

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;
}
模板
甲级{
公众:
A(std::函数f):x(f){}
模板
A(Y*x):x(x){}
私人:
boost::变体x;
}

我试图让第二个构造函数只为非std::function参数编译,这就是为什么我试图找到一种方法来显式地告诉编译器在这种情况下T应该是空的,但显然这不会编译。

您可以使用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;
}
模板
struct是_std_函数:public std::false_type{};
模板
struct是_std_函数:public std::true_type{};
模板
甲级{
公众:
A(std::函数f):x(f){}
模板
A(Y*x,typename std::enable_if<!is_std_function::value>::type*=0):x(x){
私人:
boost::变体x;
}

现在,对于std函数类型,由于第二个参数,您的构造函数无法专门化。

您可以使用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;
}
模板
struct是_std_函数:public std::false_type{};
模板
struct是_std_函数:public std::true_type{};
模板
甲级{
公众:
A(std::函数f):x(f){}
模板
A(Y*x,typename std::enable_if<!is_std_function::value>::type*=0):x(x){
私人:
boost::变体x;
}

现在,对于std函数类型,由于第二个参数,您的构造函数不能被专门化。

在您的情况下,为什么不只重载
int*
char*
?在您的情况下,为什么不只重载
int*
char*