C++模板元编程详细教程(之七)

文章介绍了C++模板元编程中处理函数类型返回值以及检查类型是否包含特定成员的方法。通过GetRet模板结构体实现了从不同类型的函数、仿函数、lambda等中提取返回类型,并利用SFINAE原则和void_t工具判断类型是否含有特定成员。
该文章已生成可运行项目,

前序文章请看:
C++模板元编程详细教程(之一)
C++模板元编程详细教程(之二)
C++模板元编程详细教程(之三)
C++模板元编程详细教程(之四)
C++模板元编程详细教程(之五)
C++模板元编程详细教程(之六)

前面我们介绍了一些基础的静态数值计算和类型处理,这一篇开始将会介绍一些进阶型的内容,做更加复杂的逻辑判断和类型处理。

函数类型的处理

如果我希望处理出一个函数类型的返回值,要怎么办呢?请看例程:

template <typename T>
struct GetRet {
   
   
};

template <typename R, typename... Args>
struct GetRet<R(Args...)> {
   
   
  using type = R;
};

template <typename T>
using GetRet_t = typename GetRet<T>::type;

// 以下是示例
int f() {
   
   return 0;}
void Demo() {
   
   
  GetRet_t<decltype(f)> a;
  std::cout << std::is_same_v<std::decay_t<decltype(a)>, int>; // true
}

我们注意到,此时的偏特化,用到了前面章节模板基础知识中的「函数类型」,也就是说,只有符合R(Args...)形式的参数才会入到这个偏特化中。那么在这种情况下,「函数类型」和「函数指针类型」就是截然不同的。也就是说下面的代码不能正确解析:

void Demo() {
   
   
  GetRet_t<decltype(f)> a; // f是函数类型,可以正确推导
  GetRet_t<decltype(&f)> b; // &f是函数指针类型,不能命中偏特化,而是会用通用模板,又因为通用模板不含type成员,因此这里报错
}

同样,仿函数类型、lambda类型、函数对象类型、成员函数类型都无法命中,进而无法取出返回值。因此,我们如果希望支持所有的情况,那就还要考虑支持其他的类型。对于仿函数和lambda类型来说,我们就要去取出它的operator ()方法的返回值类型,对于函数对象类型来说也是一样的。所以我们代码可以改造成:

template <typename T>
struct GetRet {
   
   
 private:
  using DT = std::decay_t<T>;
 public:
  // 如果内部含有operator()就取它的类型
  using type = typename GetRet<decltype(&DT::operator())>::type;
};

// 对于函数类型
template <typename R, typename... Args>
struct GetRet<R(Args...)> {
   
   
  using type = R;
};

// 对于函数指针类型
template <typename R, typename... Args>
struct GetRet<R(*)(Args...)> {
   
   
  using type = R;
};

// 对于非静态成员函数类型
template <typename T, typename R, typename... Args>
struct GetRet<R(T::*)(Args...)> {
   
   
  using type = R;
};
template <typename T, typename R, typename... Args>
struct GetRet<R(T::*)(Args...) const> {
   
   
  using type = R;
};

template <typename T>
using GetRet_t = typename GetRet<T>::type;

// 测试用例
int f() {
   
   return 0;}
struct T1 {
   
   
  int m();
};

struct T2 {
   
   
  int operator()();
};

void Demo() {
   
   
// 函数类型
  GetRet_t<decltype(f)> a;
  // 函数指针类型
  GetRet_t<decltype(&f)> b;
  // 仿函数类型
  GetRet_t<T2> c;
  // lambda类型
  GetRet_t<
本文章已经生成可运行项目
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

borehole打洞哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值