我的代码使用类似于 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风格。把一切都变成编译时值。模板?一个值。类型?一个值。值(value)观?整型常量类型的实例。
元编程现在是 constexpr 编程。
第二种方法是将一切都变成类型。
这包括模板的非类型模板参数。
template<claas 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>
作为一种类型。
关于c++ - 模板参数能否无缝地匹配类型和模板,也许作为可变参数的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156104/