简体   繁体   English

C ++串联和分层运算符

[英]C++ concatenation and strinization operator

I would like to make a shortcut for making similar function calls 我想为进行类似的函数调用提供快捷方式

int g[2];

void f1() {
   g[0] = 1;
}

void f2() {
  g[1] = 2;
}

void (*f)();

Since functions f1, f2 have some common pattern, can I make a shortcut through C++ concatenation (##) and strinization (#) operator or something else to have something like: 由于函数f1,f2具有某些通用模式,因此我可以通过C ++串联(##)和strinization(#)运算符或其他类似方式创建快捷方式:

for (int i = 0; i < 2; i++) {
   // have to do something to get the function name formed like f1, f2
   // and then assign f to f1 or f2 and call f, based on value of i
   // need help in this portion
}
template<size_t i>
void f()
{
    g[i-1] = i;
}

f<1>();
f<2>();

You can use the following approach by using an array of function pointers 您可以通过使用函数指针数组来使用以下方法

for (int i = 0; i < 2; i++) {
   void ( *pf[] )() = { f1, f2 };
   pf[i]();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM