【问题标题】:template class specialization at template constructor模板构造函数中的模板类特化
【发布时间】:2016-03-23 08:43:41
【问题描述】:

是否可以为模板类的特定特化指定模板构造函数ONLY? 我有这个代码:

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 ,但显然这赢了'不编译。

【问题讨论】:

  • 在你的情况下,为什么不只对int*char* 进行重载?

标签: c++ templates specialization boost-variant


【解决方案1】:

您可以使用 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;
}

现在对于标准函数类型,由于第二个参数,您的构造函数不能被特化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-08
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多