c++ - 用于默认模板参数的参数包

标签 c++ c++11 templates variadic-templates

我想做这样的事情:

template<int... myints>
struct A
{}

template<int... myints, class traits = A<myints...>>
struct B
{}

我知道参数包应该只出现在最后,但我记得有一些异常(exception)。您认为是否有办法使此代码(或类似代码)起作用?

谢谢

最佳答案

一种方式:

  • 将类型包装成元组。

  • 使用特化将类型列表转换为类型

#include <tuple>
#include <utility>

template<int...myints> struct A {};

namespace detail {
    template<class Sequence>
    struct make_A_from;

    template<class T, T...ts>
    struct make_A_from<std::integer_sequence<T, ts...>> {
        using type = A<ts...>;
    };
}
template<class Sequence> using make_A_from = typename detail::make_A_from<Sequence>::type;

template<class Sequence, class TraitsTuple = make_A_from<Sequence> >
struct B;

template<typename Int, Int...myints, class Traits> 
struct B<std::integer_sequence<Int, myints...>, Traits>
{
    using ints_tuple = std::tuple<std::integral_constant<Int, myints>...>;
    using traits_type = Traits;
};

namespace detail {
    template<typename Int, Int...is>
    struct make_B
    {
        using type = B<std::integer_sequence<Int, is...>>;
    };
}

template<int...is> using make_B = B<std::integer_sequence<int, is...>>;

int main()
{
    make_B<1,3,4,5> b;
    B<std::integer_sequence<int, 5,6,7,8>> b2;
    B<std::integer_sequence<int, 5,6,7,8>, class CustomTrait> b3;
}

关于c++ - 用于默认模板参数的参数包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45375266/

相关文章:

c++ - 函数调用语法?

c++ - 如何拥有具有类型和大小的可变模板?

c++ - 如何将代码结果(在 void 函数内)写入 C++ 中的文本文件

python - 无法在Python中调用C++类函数

c++ - 为什么 Multimap 不将一个索引处的所有值写入文本文件?

c++ - 在生命周期有限的多个模块之间共享 std::function

c++ - 在非线程安全容器中访问指针指向的值(线程安全映射中的条目)是否可以?

c++ - 存储表达式模板仿函数

c++ - gmock 和转发声明的类

c++ - 为什么 C++11 包含一个关于比较 void 指针的奇怪子句?