【问题标题】:Partial template specialization based on argument traits基于参数特征的部分模板特化
【发布时间】:2014-03-06 22:45:59
【问题描述】:

假设我有以下模板:

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&lt;T&gt; 永远不会被简单地破坏(因此不是文字类型)。我希望喜欢有一个像

这样的部分专业化
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) {};
};

T 存在时,让example&lt;T&gt; 被轻易破坏,但不幸的是,这给了我(事后看来是合理的)警告

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

那么有什么方法可以在这里得到我想要的吗?

【问题讨论】:

  • 为什么需要显式写dtor?你不能=default吗? (或者,如果它的隐式定义被删除,这是不可能的吗?)
  • 唉,=default 设置析构函数被删除,如果T 不是一般可破坏的,至少在clang 3.4 上是这样。
  • @dyp:这对工会来说没有意义。参见 9.5/2:析构函数必须由用户提供。
  • @KerrekSB 是的,我不确定显式默认是否会覆盖(隐式)=delete。它不是。 [dcl.fct.def.default]/4

标签: c++ template-specialization sfinae


【解决方案1】:

也许有第二个默认模板参数?

#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{{}};
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多