为结构成员创建别名

Cri*_*_SO 0 c++

我有以下代码:

struct context {
  int a, b;
};

int fn(struct context *c) {
  // create local aliases
  int &a = c->a;
  int &b = c->b;
  // use as if these were local variables
  return a+b;
}
Run Code Online (Sandbox Code Playgroud)

是否可以自动创建fn允许访问ab不访问的变量别名c->

int fn(struct context *c) {
  // magic line that is not dependent on the list of the members
  return a+b;
}
Run Code Online (Sandbox Code Playgroud)

允许我自动执行此操作而无需列出所有变量的东西。

我需要这个 C++ 代码生成器 (SWIG),它可以让我大大简化模板。

P K*_*mer 7

您可以像这样使用结构化绑定(需要 C++17): https://en.cppreference.com/w/cpp/language/structured_binding

#include <iostream>

struct context 
{
    int a, b;
};

int fn(const context& ctx)
{
    // structured binding only has to know how many members a struct has, not even their names. 
    auto& [a, b] = ctx;
    return a + b;
}

int main()
{
    context ctx{ 1,2 };
    std::cout << fn(ctx);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)