c++串联和字符串化操作符

C++ concatenation and strinization operator

本文关键字:操作符 字符串 c++      更新时间:2023-10-16

我想创建一个快捷方式来进行类似的函数调用

int g[2];
void f1() {
   g[0] = 1;
}
void f2() {
  g[1] = 2;
}
void (*f)();

由于函数f1, f2有一些共同的模式,我可以通过c++连接(##)和字符串化(#)操作符或其他方式创建一个快捷方式,如:

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>();

通过使用函数指针数组

,可以使用以下方法
for (int i = 0; i < 2; i++) {
   void ( *pf[] )() = { f1, f2 };
   pf[i]();
}