你可以使用
Boost.Preprocessor在C++98中模拟可变参数模板。实际上,在幕后所做的是预处理器为不同数量参数的所有特化写入模板。现在,您可以在
varadic<...>::type
中使用typedef,最多有256个模板参数。
对于模板,这并不是一个问题,因为只有实例化的模板进入二进制文件,但对于非模板实体,这可能导致代码膨胀。
#include <iostream>
#include <boost/preprocessor/config/limits.hpp>
#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/facilities/intercept.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#define MAKE_VARIADIC(Z, N, _) \
template < \
typename R \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(Z, N, typename T) \
> \
struct variadic < R BOOST_PP_ENUM_TRAILING_PARAMS_Z(Z, N, T) > \
{ \
typedef R (*type)(BOOST_PP_ENUM_PARAMS_Z(Z, N, T)); \
};
template <
typename R
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(BOOST_PP_LIMIT_ITERATION, typename T, = void BOOST_PP_INTERCEPT)
>
struct variadic;
BOOST_PP_REPEAT(BOOST_PP_LIMIT_ITERATION, MAKE_VARIADIC, nil)
template < typename T >
void print_T()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
int main ()
{
print_T< variadic<int, double, float>::type > ();
}
在Wandbox上的演示
然而,使用C++11的别名模板会更加方便处理这种情况,在2017年,标准定稿后六年,没有理由不切换到C++11。仍在使用C++98就像仍在使用Windows XP一样过时。
#include <iostream>
template <typename R, typename ... Args>
using pf = R(*)(Args...);
template < typename T >
void print_T()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
int main ()
{
print_T< pf<int, double, float> > ();
}
在 Wandbox 上的演示