C++ std::enable_if 代码示例

std::enable_if 在C++ 14中的定义为:

template< bool B, class T = void >
using enable_if_t = typename enable_if<B,T>::type;

对应的执行内容为以下二者之一:

template<bool B, class T = void>
struct enable_if {}; //此时B为false
 
template<class T>
struct enable_if<true, T> { typedef T type; }; //此时B为true

代码示例:

#include <type_traits>
#include <iostream>
 
// foo1 overloads are enabled via the return type
template<class T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type 
    foo1(T t) 
{
    std::cout << "foo1: float\n";
    return t;
}
 
template<class T>
std::enable_if_t<std::is_integral<T>::value, T> //Using helper type
    foo1(T t) 
{
    std::cout << "foo1: int\n";
    return t;
}
 
// foo2 overload is enabled via a parameter
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = 0) 
{
    return t;
}
 
// foo3 overload is enabled via a template parameter
template<class T ,
         typename std::enable_if<std::is_integral<T>::value>::type* = nullptr >
T foo3(T t) // note, function signature is unmodified
{
    return t;
}
 
// A is enabled via a template parameter
template<class T, class Enable = void>
class A; // undefined
 
template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value >::type> {
}; // note: for this use case, static_assert may be more appropriate
 
int main()
{
    foo1(1.2); // OK, calls the first version of foo1()
    foo1(10); // OK, calls the second version of foo1()
 
//  foo2(0.1); // compile-time error
    foo2(7); // OK
 
//  foo3(1.2); // compile-time error
    foo3(34); // OK
 
//  A<int> a1; // compile-time error
    A<double> a1; // OK
}

输出为:

foo1: float
foo1: int
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值