boost.preprocessor
可以做这种事情,你可以在这里获得下降教程:预处理器元编程简介
对于您的具体示例,这是我想出的代码(注意:我只是在预处理器下运行它以检查生成的代码是否是我所期望的,但没有尝试编译代码本身)。
这同时使用了enum_params
帮助生成属性列表的宏local_iterate
允许用一系列参数扩展宏。我还有一个宏 if 可以用“:”与“,”来处理发送到流的第一个参数的特殊情况。
总的来说,当你开始了解如何boost.preprocessor
工作中寻找您需要的功能参考手册变得相对容易,并且在大多数编译器支持可变参数模板之前,它是一个“合理”的替代品。请注意,它在编译时非常密集,因此请谨慎使用。
编辑:虽然我确实认为这是一个相对简单的示例的一般练习,但我确实同意,就使用 synek317 建议的伪流类对这个特定示例进行编码而言,将是一个更灵活和“轻量级”的解决方案。同样,实现此类流不需要您对所有运算符进行专门化,事实上 boost 再次提供 IOStreams 库来帮助您将类实现为标准 C++ 流(http://www.boost.org/doc/libs/1_52_0/libs/iostreams/doc/index.html)
#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/control/if.hpp>
# ifndef MY_SEND_MAX
# define MY_SEND_MAX 15
# endif
/*
* macros called through BOOST_PP_REPEAT to generate lists
* J : I don't know what it is
* I : the current counter number
* D : the 3rd argument of BOOST_PP_REPEAT
*/
// Generate the list of arguments after std::string
# define MY_SEND_PARAM(J,I,D) , BOOST_PP_CAT(const T,I) & BOOST_PP_CAT(arg,I)
// Generate the stream's <<s adter the string
# define MY_SEND_STREAM(J,I,D) <<BOOST_PP_IF(I,",",": ")<<BOOST_PP_CAT(arg,I)
/*
* Macro to call for generating onde function
* N : the number of arguments
*/
// Create one function with a string and N extra aarguments
# define MY_SEND(N) \
template<BOOST_PP_ENUM_PARAMS(N,typename T)> \
void send(std::string const &fn BOOST_PP_REPEAT(N,MY_SEND_PARAM,~)) { \
std::ostringstream s; \
s<<fn BOOST_PP_REPEAT(N,MY_SEND_STREAM,~); \
sendMessage(s.str()); \
}
// End of my macro
/*
* BOOST_PP local loop to generate all the the function
*/
// What macro to call in the loop
#define BOOST_PP_LOCAL_MACRO(n) MY_SEND(n)
// do the job form 0 to MY_SEND_MAX
#define BOOST_PP_LOCAL_LIMITS (0,MY_SEND_MAX)
// execute the loop
#include BOOST_PP_LOCAL_ITERATE()
// undefine all my stuff
# undef MY_SEND_PARAM
# undef MY_SEND_STREAM
# undef MY_SEND
# undef BOOST_PP_LOCAL_MACRO
# undef BOOST_PP_LOCAL_LIMITS