使用C++中的宏生成函数

Generating functions with macros in C++

本文关键字:函数 C++ 使用      更新时间:2023-10-16

我有以下宏,旨在在当前作用域或命名空间中生成函数:

#define MAKE_FUNC(FNAME) 
template <typename T> 
T ##FNAME## (const T& t) 
{
   return t; 
}
MAKE_FUNC(foo)
MAKE_FUNC(boo)
int main()
{
   foo(1);
   boo(2);
}

以下是编译上述代码时的错误消息:

prog.cpp:8:1: error: pasting "Tfoo" and "(" does not give a valid preprocessing token
prog.cpp:9:1: error: pasting "Tboo" and "(" does not give a valid preprocessing token
prog.cpp:8: error: ISO C++ forbids declaration of ‘Tfoo’ with no type
prog.cpp:9: error: ISO C++ forbids declaration of ‘Tboo’ with no type
prog.cpp: In function ‘int main()’:
prog.cpp:13: error: ‘foo’ was not declared in this scope
prog.cpp:14: error: ‘boo’ was not declared in this scope

http://ideone.com/paiu1

似乎串联失败了,这个问题到底有问题吗?

你想要

T FNAME (const T& t) 

##连接,您不想连接。