[英]#define/macro to return a function pointer to a function given in the same file
Say I have code说我有代码
void 1funct() {
(...)
}
void 2funct() {
(...)
}
etc., to
void nfunct() {
(...)
}
Is it possible to return the function pointer to the correct function given an n by是否可以将 function 指针返回到正确的 function 给定的 n 由
#define RET_FUNC_POINTER(n) (&nfunct);
? ?
Yes — macros can concatenate source code characters into a single token using ##
:是的 — 宏可以使用
##
将源代码字符连接成单个标记:
#define RET_FUNC_POINTER(n) (&n ## funct);
(Tokens are the invisible "building blocks" of your source code, discrete units of text that the parser generates from your code while trying to understand your program. They are roughly analogous to "words" in English, but they do not need to be separated by spaces in C++ unless omitting a space would just produce a single token: eg int main
vs intmain
, but int *
vs int*
. With ##
we can take the two would-be tokens int
and main
, and use the preprocessor to force them into intmain
instead. Just, one of your arguments is a "variable" to the macro. Notice that you don't need to join &
and the n ## funct
part, as the &
is already a separate token, and should remain that way.) (标记是源代码中不可见的“构建块”,是解析器在尝试理解您的程序时从您的代码生成的离散文本单元。它们大致类似于英语中的“单词”,但它们不需要在 C++ 中用空格分隔,除非省略空格只会产生一个标记:例如
int main
vs intmain
,但int *
vs int*
。使用##
我们可以获取两个可能的标记int
和main
,并使用预处理器而是强制它们进入intmain
。只是,您的 arguments 之一是宏的“变量”。请注意,您不需要加入&
和n ## funct
部分,因为&
已经是一个单独的标记,并且应该保持这种状态。)
However, you may wish to consider a nice array of pointers instead.但是,您可能希望考虑一个不错的指针数组。
If the n
is known statically at compile-time (which it must be for your macro to work) then you don't really gain anything over just writing &1funct
, &2funct
etc other than obfuscating your code (which isn't a gain).如果
n
在编译时是静态已知的(它必须是你的宏才能工作),那么除了混淆你的代码(这不是一个收获)之外,仅仅编写&1funct
, &2funct
等你并没有真正获得任何东西。
Also note that your function names cannot start with digits;另请注意,您的 function 名称不能以数字开头; you'll have to choose a different naming scheme.
您必须选择不同的命名方案。
Not sure why you want to do this (instead of just using a const
array), but it's quite easy to do with a macro:不知道为什么要这样做(而不仅仅是使用
const
数组),但使用宏很容易做到:
#define RET_FUNC_POINTER(n) (n##funct)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.