前序文章请看:
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<

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

被折叠的 条评论
为什么被折叠?



