基于参数特征的部分模板专业化(Partial template specialization based on argument traits)

编程入门 行业动态 更新时间:2024-10-24 08:27:40
基于参数特征的部分模板专业化(Partial template specialization based on argument traits)

假设我有以下模板:

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>可以轻易破坏,但不幸的是,这给了我(合理的,事后看来)的警告

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

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

Suppose I have the following template:

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() {}; };

Because of the destructor there, example<T> will never be trivially destructible (and thus not, say, a literal type). I'd like to have a partial specialization like

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

to let example<T> be trivially destructible when T is, but unfortunately that gives me the (reasonable, in hindsight) warning

warning: class template partial specialization contains a template parameter that can not be deduced; this partial specialization will never be used

So is there any way to get what I want here?

最满意答案

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

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

Maybe with a second, defaulted template parameter?

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

更多推荐

本文发布于:2023-04-28 00:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329662.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特征   模板   参数   Partial   template

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!