首页 > 解决方案 > 如何指定接受任何类型或值的参数包?

问题描述

在为类型指定参数包时,我希望不仅能够接受typenames,而且能够接受任意类型的值。例子:

template <thing... Things>
//        ^^^^^   <- pseudo code
struct Example {};

Example<int,bool>();
Example<4,float,'x'>();

显然,thing不是一个有效的 C++ 关键字,但这里表达的想法是否可能?


上下文是我有一个容器适配器,它想要将自己的值类型插入到容器中,但允许传递任何其他模板参数,并且一些容器不仅接收类型参数,还接收值(std::array将是一个流行的例子)。

template <template <typename...> typename Container, typename... Args>
struct Adapter {
  struct Node { /* ... */ };
  Container<Node,Args...> container;
};

Adapter<std::vector>(); // fine
Adapter<std::vector,MyAllocator>(); // fine
Adapter<std::array,3>(); // nope because 3 is not a typename

标签: c++templatesvariadic-templatesparameter-pack

解决方案


推荐阅读