【发布时间】:2012-05-15 20:28:53
【问题描述】:
我有以下宏,旨在在当前范围或命名空间中生成函数:
#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
连接好像失败了,有没有解决这个问题?
【问题讨论】:
-
连接没有失败。它完全按照宣传的方式工作。不过,您似乎不想要串联。
-
我知道我应该是我的一切我-OK-youre-OK,但宏大部分时间都很糟糕。
-
@R.MartinhoFernandes:非常正确。 :)
-
除了不想连接之外,还试图连接任何东西,'(' 在某些编译器上会创建一个“无效标记”。一些编译器会直接吞掉它。并没有真正激励自己成为预处理器专家...我不知道哪个是对的。
标签: c++ function templates macros