c++ - 在 C++ 中使用宏生成函数

标签 c++ function templates macros

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

#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) \

## 拼接,你不想拼接。

关于c++ - 在 C++ 中使用宏生成函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10608416/

相关文章:

c++ - 使用 sfml vector 的模板函数重载解决方案

c++ - 模板参数的乘法

c++ - 通过递归解决方案计算最长递增子序列的数量

C 函数中的 Const 声明和实现

function - 函数输入进行求和运算的求和问题

c - 从 c 中的函数返回指针是好习惯吗?

c++ - 在不更改成员范围的情况下有条件地启用静态成员

c++ - C++ 中的 TCHAR* 到 char* 转换

c++ - "Overloading"模板化和非模板化类型

c++ - RegOpenKeyEx 和 RegSetValueEx 失败,但我不知道为什么