c++ - boost::function 如何支持不同长度模板参数的模板类

标签 c++ templates boost boost-function boost-preprocessor

我想使用 boost 预处理器来声明具有不同模板变量长度的模板类,基本上就像 boost::function 所做的那样。

#if !BOOST_PP_IS_ITERATING

#ifndef D_EXAMPLE_H
#define D_EXAMPLE_H
#include <boost/function>
#include <boost/preprocessor/iteration/iterate.hpp>
#define BOOST_PP_ITERATION_PARAMS_1 (3, (1, 2, "example.h"))
#include BOOST_PP_ITERATE()

#else
template<class T, BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class T)>
class Example
{
    boost::function<T, (BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), T))> func;
};
#endif

上面的代码显然不会工作,因为它在同一个头文件中声明了具有不同模板变量长度的同一个类。我想要实现的是包含一个文件并定义具有不同模板变量长度的类,就像 boost::function 一样。

#include "example.h"
Example<int, int, float> example1;
Example<double, int> example2;

我查阅了 boost::function 的代码,但我无法弄清楚它是如何工作的。有任何想法吗?

最佳答案

需要先声明参数最多的模板类,除第一个参数外,所有参数都使用默认值。然后可以将具有较少参数的模板类定义为主模板类的特化。示例:

#include <iostream>

template<class A, class B = void, class C = void>
class Example
{
public:
    static const int x = 3;
};

template<class A, class B>
class Example<A, B, void>
{
public:
    static const int x = 2;
};

template<class A>
class Example<A, void, void>
{
public:
    static const int x = 1;
};

int main()
{
    Example<int, int, int> e3;
    Example<int, int> e2;
    Example<int> e1;
    std::cout << e3.x << e2.x << e1.x << std::endl;
}

关于c++ - boost::function 如何支持不同长度模板参数的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7875138/

相关文章:

c++ - 有没有办法关闭 C++ 和 Rust 编译的循环优化?

JavaScript 模板“不给糖就捣蛋”?

c++ - 构建 cpp-netlib 失败 - 未添加 lib 前缀

c++ - 错误 C4430 : missing type specifier - int assumed. 注意:C++ 不支持我的构造函数的默认整数

c++ - C++ 临时变量的生命周期

c++ - 嵌套类中的别名模板

c++ - 如何从程序中删除日志调试语句

C++ 和设计一个 OO 类

c++ - 从排序的 std::vector 中删除除最后一个具有相同键的元素之外的所有元素的最简洁方法?

java - 使用 SVN 将一些模板文本包含到源文件中的好解决方案?