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

标签 c++ templates typedef c++98

here 相同的问题除了使用 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 中使用 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>

// 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

关于c++ - 定义 typedef 的可变参数模板(使用 C++98),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44060631/

相关文章:

c++ - 类模板继承 C++

c++ - 提前调用对应于ANOTHER模板函数的所有可能的模板函数

c - typedef 结构在语法上是如何工作的?

c++ - 验证电话号码和手机号码

c++ - 从 HDC 句柄创建 QPaintDevice

c++ - 从 DLL 导出前向声明的类

c++ - 内置类型的析构函数(int、char 等)

C++ boost asio : bind: Address already in use

java - 用于创建文本文件的 java 模板引擎/api 是什么?

c++ - 为 typedef 的函数指针推导模板参数