c++ - 模板参数能否无缝地匹配类型和模板,也许作为可变参数的一部分?

标签 c++ templates c++17 auto variadic

我的代码使用类似于 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>作为表示非类型模板参数的类型 77array<int,k<77>>得到 std::array<int,77> .

纯类型数组模板现在很容易元编程。只需编写一次这些包装器,然后进行元编程。

传递模板可以是:

template<template<class...>class> struct Z{};

现在我们可以通过 Z<array>作为一种类型。

关于c++ - 模板参数能否无缝地匹配类型和模板,也许作为可变参数的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156104/

相关文章:

c++ - 将 armadillo/blas/lapack 与 cmake 链接(对 `dgemv_' 的 undefined reference )

c++ - 将精确表示分配给浮点值

c++ - 如何以可维护的方式为整个类层次结构保护析构函数?

C++ 实现模板化嵌套类时遇到问题

c++ - 您将如何缩短它以便 action1 和 action2 在代码中只出现一次?

c++ - 错误 MSB6006 : "CL.exe" exited with code 1 after adding template function or class

c++ - 您自己的类型的结构化绑定(bind)不是结构或元组(通过公共(public)成员函数)

c++ - 尝试将值存储到映射中的std::variant时,std::bad_variant_access错误

c++ - 如何将 recursive_directory_iterator 与算法库一起使用,尤其是 std::remove_if?

使用类型特征调用 C++ 条件函数