在C ++中使用宏生成函数 [英] Generating functions with macros in C++
本文介绍了在C ++中使用宏生成函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下宏用于在当前作用域或命名空间中生成函数:
#define MAKE_FUNC )\
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:错误:粘贴Tfoo和(没有给出有效的预处理令牌
prog .cpp:9:1:错误:粘贴Tboo和(没有给出有效的预处理令牌
prog.cpp:8:error:ISO C ++禁止声明'Tfoo'没有类型
prog.cpp:9:error:ISO C ++禁止没有类型
的'Tboo'声明prog.cpp:在函数'int main()'中:
prog.cpp:13:error: foo'未在此范围中声明
prog.cpp:14:错误:'boo'未在此范围中声明
解决方案
你想要
T FNAME(const T& t)\
##
连接,您不想连接。
I have the following macro that is intended to generate functions in the current scope or namespace:
#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);
}
The following is the error message when compiling the above code:
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
It seems like the concatenation has fail, is there anyway around this problem?
解决方案
You want
T FNAME (const T& t) \
##
concatenates, you don't want to concatenate.
这篇关于在C ++中使用宏生成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文