12

C++代码赏析:获取结构体成员个数

C++20

  • consteval :立即函数,要求编译器求值
  • requires:requires 表达式,它是 bool 类型的纯右值表达式,描述对一些模板实参的约束。这种表达式在约束得到满足时是 true,否则是 false:
  • T{ Args... }:聚合初始化,从花括号初始化器列表初始化聚合体。
  • operator T():用户定义转换函数,允许从类类型到其他类型的隐式转换显式转换
  • 递归调用过程:
  1. CountMember()-
  2. CountMember(AnyType)
  3. CountMember(AnyType,AnyType)
  4. CountMember(AnyType,AnyType,AnyType)
  5. sizeof...(Args) - 1 相当于3-1=2
#include 
#include 
#include 

struct Point {
    double x;
    double y;
};
 
struct AnyType {
    template 
    operator T();
};

template 
consteval size_t CountMember(auto&&... Args) {
    if constexpr (! requires { T{ Args... }; }) { // (1)
        return sizeof...(Args) - 1;
    } else {
        return CountMember(Args..., AnyType{}); // (2)
    }
}

int main(int argc, char** argv) {
    struct Test { int a; int b; int c; double d; };
    printf("Test:%zu
", CountMember());
    printf("Point:%zu
", CountMember());
}

运行结果:

Test:4
Point:2
C++代码赏析:获取结构体成员个数

在线测试代码

https://wandbox.org/

C++11

#include 
#include 
#include 

template< class... >
using void_t = void;

struct Point {
    double x;
    double y;
};

struct AnyType {
    template 
    operator T();
};

template 
struct CountMember {
    constexpr static size_t value = sizeof...(Ts) - 1;
};

template 
struct CountMember, Ts...> {
    constexpr static size_t value = CountMember::value;
};

int main(int argc, char** argv) {
    struct Test { int a; int b; int c; double d; };
    printf("Test:%zu
", CountMember::value);
    printf("Point:%zu
", CountMember::value);
}
13
发表评论
留言与评论(共有 0 条评论) “”
昵称:
匿名发表 登录账号
         
   
验证码:

相关文章

推荐文章

10
11