基于参数特征的部分模板专业化

时间:2014-03-06 22:45:59

标签: c++ template-specialization sfinae

假设我有以下模板:

template <typename T> union example {
    T t;

    constexpr example(const T & t) : t(t) {};

    /* We rely on owning class to take care
     * of destructing the active member */
    ~example() {};
};

由于那里有析构函数,example<T>永远不会被轻易破坏(因此不是文字类型)。我喜欢有一个像

这样的部分专业化
template <typename T> union
    example<std::enable_if_t<std::is_trivially_destructible<T>::value, T>> {
    T t;

    constexpr example(const T & t) : t(t) {};
};

example<T>T时可以轻易破坏,但不幸的是,这给了我(合理的,事后警告)警告

  

警告:类模板部分特化包含模板   无法推导出的参数;         这部分专业化将永远不会被使用

那么有什么方法可以得到我想要的东西吗?

1 个答案:

答案 0 :(得分:6)

可能使用第二个默认模板参数?

#include <type_traits>
#include <iostream>

template <typename T, bool = std::is_trivially_destructible<T>::value>
union example {
    T t;

    constexpr example(const T & t) : t(t) {};

    /* We rely on owning class to take care
     * of destructing the active member */
    ~example() { std::cout << "primary template\n"; }
};

template<typename T>
union example<T, true> {
    T t;

    constexpr example(const T & t) : t(t) {};
};


struct nontrivial
{
    ~nontrivial() { std::cout << "woot!\n"; }
};

int main()
{
    example<nontrivial> e1{{}};
    example<int> e2{{}};
}
相关问题