【发布时间】:2015-09-13 21:27:26
【问题描述】:
我有以下问题。我有一些类执行输入数组到输出数组的映射。我想要浮点类型,以及数组的长度作为模板参数,所以映射类看起来像这样:
template <typename FloatType, std::size_t input, std::size_t output>
class Mapper
{};
template <typename FloatType, std::size_t input, std::size_t output>
class FirstMapper : public Mapper<FloatType, input, output>
{};
template <typename FloatType, std::size_t input, std::size_t output>
class SecondMapper : public Mapper<FloatType, input, output>
{};
到目前为止一切顺利。我的目标是编写一个类来堆叠这些 Mapper 类的不同实例。我希望能够编写这样的代码:
StackedMapper<
double, // the FloatType, obviously
input_1, // the size of the first mapper's input array
FirstMapper, // the template template type of the first mapper
input_2, // the size of the first mapper's output and
// second mapper's input array
SecondMapper, // the template template type of the second mapper
input_3, // the size of the second mapper's output and
// third mapper's input array
FirstMapper, // the template template type of the third mapper
output // the size of the third mapper's output array
// ... any additional number of Mapper classes plus output sizes
> stacked_mapper;
在内部,StackedMapper 类应将映射器实例存储在 std::tuple 中。我希望元组具有以下类型:
std::tuple<
FirstMapper<double, input_1, input_2>,
SecondMapper<double, input_2, input_3>,
FirstMapper<double, input_3, output>
// ...
>;
如省略号所示,我想添加任意数量的 Mapper 类。正如您可能从 cmets 中看到的那样,一层的输出大小等于下一层的输入大小。对于堆栈中的所有映射器,浮点类型只会定义一次。
有人有想法吗?我见过this 问题,它解决了交替类型(整数常量和类型)问题,但它似乎不适用于模板模板参数,因为我总是收到类似expected a type, got 'FirstMapper' 的错误。
有人对此有想法吗?
【问题讨论】:
-
如果你对所有东西都使用类型,而不是模板模板参数和非类型模板参数,这会更方便。阅读@Yakk 的元编程答案之一以获取一些示例,例如stackoverflow.com/a/32056973
-
@dyp:感谢您发布该链接,这很好
标签: c++ templates variadic-templates template-meta-programming