联合类型的模板特化
Template specialization for union type
如何为 union
类型专门化模板?假设我有模板函数
template <typename T>
void foo(T value);
如果 T
不是任何 union
类型,我想禁止调用此函数。我怎样才能做到这一点?
为此,您可以使用 std::enable_if
(std::enable_if_t
) 和 <type_traits>
中的 std::is_union
。类似于:
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 规则的解释。
I want to prohibit calling this function if T is not any union type. How can I achieve this?
也许 std::is_union
?
template <typename T>
std::enable_if_t<std::is_union<T>::value> foo(T value)
{ /* ... */ }
如何为 union
类型专门化模板?假设我有模板函数
template <typename T>
void foo(T value);
如果 T
不是任何 union
类型,我想禁止调用此函数。我怎样才能做到这一点?
为此,您可以使用 std::enable_if
(std::enable_if_t
) 和 <type_traits>
中的 std::is_union
。类似于:
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 规则的解释。
I want to prohibit calling this function if T is not any union type. How can I achieve this?
也许 std::is_union
?
template <typename T>
std::enable_if_t<std::is_union<T>::value> foo(T value)
{ /* ... */ }