模板参数是否可以无缝匹配类型和模板,也许是可变变量的一部分

Can template parameters match both types and templates seamlessly, perhaps as part of a variadic?

本文关键字:也许 变量 一部分 是否 参数 类型      更新时间:2023-10-16

我的代码使用类似于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)

有两种相关的方法。

首先是助推哈纳风格。 将所有内容转换为编译时值。 模板? 一个值。 类型? 一个值。 值? 类似整数常量的类型的实例。

元编程现在是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>作为类型传递。