我的代码使用类似于
Boost.PolyCollection
中的静态类型构造来存储一些状态。
我认为,我的问题至少可以通过下面的代码来说明。基本上,我正在使用参数包,并且需要一种通过包中的内容“实例化”给定模板的方法。
#include <unordered_map>
template<typename... Ts>
struct Pack
{
/*
instantiate a given template with passed types + the types in this Pack
but passed Template may take non-type template parameters, what to do??
*/
// template<template<typename...> class Template, typename... As> // error: type/value mismatch at argument 1 in template parameter list for 'template<class ... Ts> template<template<template<class ...> class Template, class ... As> template<class ... Ts> template<class ...> class Template, class ... As> using Inst = Template<As ..., Ts ...>'
// using Inst = Template<As..., Ts...>;
// this works for my case, but it's too specific and ugly -
// am fixing the first of As to be a non-type
template<template<template<typename...> class, typename...> class Template, template<typename...> class A1, typename... As>
using Inst = Template<A1, As..., Ts...>;
};
template<template<typename...> class Segment, typename Key, typename... Ts>
class AnyMap
{
};
int main()
{
typedef Pack<int, char> ServicePack;
typedef long Key;
using ServiceMap = typename ServicePack::template Inst<AnyMap, std::unordered_map, Key>; // AnyMap with given segment type and key
}
我希望
auto...
(我没怎么用过)来救援,但似乎 auto
不会匹配模板模板参数,它仅适用于推断类型的值。
您知道实现这一目标的简单方法吗?
(也许显然,这是关于 c++17 的)
有两种相关的方法。
首先是boost hana风格。将所有内容都转换为编译时值。模板?一个值。类型?一个值。价值观?整数常量类型的实例。
元编程现在是 constexpr 编程。
第二种方法是将一切都变成类型。
这包括模板的非类型模板参数。
template<class T, class N>
using array=std::array<T,N{}()>;
template<auto x>
using k=std::integral_constant<decltype(x), x>;
现在我们可以将
k<77>
作为表示非类型模板参数 77
的类型传递给 array<int,k<77>>
并得到 std::array<int,77>
。
纯类型数组模板现在很容易使用元编程。只需编写一次这些包装器,然后进行元编程即可。
传递模板可以是:
template<template<class...>class> struct Z{};
现在我们可以将
Z<array>
作为类型传递。