c++ enable_if的使用技巧有哪些
导读:使用enable_if来限制模板函数的特化 template <typename T> typename std::enable_if<std::is_integral<T>::value, T>::t...
- 使用enable_if来限制模板函数的特化
template <
typename T>
typename std::enable_if<
std::is_integral<
T>
::value, T>
::type
foo(T t) {
return t * 2;
}
template <
typename T>
typename std::enable_if<
std::is_floating_point<
T>
::value, T>
::type
foo(T t) {
return t * 3.14;
}
- 使用enable_if来限制模板类的特化
template <
typename T, typename = std::enable_if_t<
std::is_integral<
T>
::value>
>
class MyClass {
// class implementation
}
;
template <
typename T, typename = std::enable_if_t<
std::is_floating_point<
T>
::value>
>
class MyClass {
// class implementation
}
;
- 使用enable_if来选择模板函数的返回类型
template <
typename T>
std::enable_if_t<
std::is_integral<
T>
::value, T>
foo(T t) {
return t * 2;
}
template <
typename T>
std::enable_if_t<
std::is_floating_point<
T>
::value, T>
foo(T t) {
return t * 3.14;
}
- 使用enable_if来限制模板函数的参数类型
template <
typename T, typename U,
typename = std::enable_if_t<
std::is_integral<
T>
::value &
&
std::is_integral<
U>
::value>
>
void bar(T t, U u) {
// function implementation
}
template <
typename T, typename U,
typename = std::enable_if_t<
std::is_floating_point<
T>
::value &
&
std::is_floating_point<
U>
::value>
>
void bar(T t, U u) {
// function implementation
}
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++ enable_if的使用技巧有哪些
本文地址: https://pptw.com/jishu/688285.html