Bob*_*Bob 6 c++ templates typedef c++98
除了使用 C++98 之外,与此处相同的问题:
我刚刚定义了 4 个不同的 typedef,它们的差异很小,我想知道是否有办法使用模板来更有效地做到这一点。
我的 typedef 是以下形式: typedef Type1 (*pf)(Type2, Type3, ...)
我如何模板这个typedef?
只Type1需要。
我手动写:
typedef int (*pf)(int)
typedef bool (*pf)()
typedef char (*pf)(bool, int)
Run Code Online (Sandbox Code Playgroud)
我正在寻找类似的东西:
template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)
Run Code Online (Sandbox Code Playgroud)
那是对的吗?
您可以使用Boost.Preprocessor来模拟 C++98 中的可变参数模板。实际上在幕后所做的事情是,预处理器为您编写针对不同数量参数的模板的所有专业化。您现在可以将 typedefvaradic<...>::type与最多 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>
// Macro to generate specializations
#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)); \
};
// Declare variadic struct with maximum number of parameters
template <
typename R
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(BOOST_PP_LIMIT_ITERATION, typename T, = void BOOST_PP_INTERCEPT)
>
struct variadic;
// Repeat macro to create all specializations
BOOST_PP_REPEAT(BOOST_PP_LIMIT_ITERATION, MAKE_VARIADIC, nil)
// Function to print what was derived
template < typename T >
void print_T()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
// Test
int main ()
{
print_T< variadic<int, double, float>::type > ();
}
Run Code Online (Sandbox Code Playgroud)
然而,对于这种事情,使用 C++11 别名模板要方便得多,在标准批准 6 年后的 2017 年的今天,没有理由不切换到 C++11。仍然使用 C++98 有点像仍然使用 Windows XP。
#include <iostream>
template <typename R, typename ... Args>
using pf = R(*)(Args...);
// Function to print what was derived
template < typename T >
void print_T()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
// Test
int main ()
{
print_T< pf<int, double, float> > ();
}
Run Code Online (Sandbox Code Playgroud)