定义 typedef 的可变参数模板(使用 C++98)

Variadic template to define a typedef (using 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)

我正在寻找类似的东西:

template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)

对吗?

您可以使用 Boost.Preprocessor 来模拟 C++98 中的可变参数模板。实际上在幕后完成的是预处理器为您为不同数量的参数编写模板的所有特化。您现在可以在 varadic<...>::type 中使用最多 256 个模板参数的 typedef。

使用模板就不是这样的问题,因为只有实例化的模板会进入二进制文件,但对于非模板实体,这可能会导致大量代码膨胀。

#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 > ();
}

Demo on Wandbox


然而,对于这种事情,使用 C++11 别名模板要方便得多,2017 年的今天,标准被批准 6 年后,没有理由不切换到 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> > ();
}

Demo on Wandbox