【发布时间】:2019-05-09 17:39:58
【问题描述】:
如何为union 类型专门化模板?假设我有模板函数
template <typename T>
void foo(T value);
如果T 不是任何union 类型,我想禁止调用此函数。我怎样才能做到这一点?
【问题讨论】:
标签: c++ templates union sfinae
如何为union 类型专门化模板?假设我有模板函数
template <typename T>
void foo(T value);
如果T 不是任何union 类型,我想禁止调用此函数。我怎样才能做到这一点?
【问题讨论】:
标签: c++ templates union sfinae
如果 T 不是任何联合类型,我想禁止调用此函数。我怎样才能做到这一点?
也许std::is_union ?
template <typename T>
std::enable_if_t<std::is_union<T>::value> foo(T value)
{ /* ... */ }
【讨论】:
为此,您可以使用 std::enable_if (std::enable_if_t) 和 std::is_union 中的 <type_traits>。比如:
template <class T,
typename std::enable_if_t<std::is_union<T>::value,
int> = 0>
void foo(T t) {
// an implementation for union types
}
这里是SFINAE 规则的解释。
【讨论】: