2012-05-15 44 views
2

我有以下宏旨在产生在当前范围内的功能或命名空间:生成函数

#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

好像串联有失败,反正是有解决这个问题?

+2

连接并未失败。它的工作与广告完全一样。看起来你并不想要连接。 –

+2

我知道我应该是所有我很好,你很好,但是*宏大部分时间都是*。 –

+1

@ R.MartinhoFernandes:非常真实。 :) –

回答

10

你想

T FNAME (const T& t) \ 

##会连接,你不想来连接。

+0

这样做很不错。 –