gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:24:24 25 4
gpt4 key购买 nike

我想做这样的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com