将STD ::变体转换为STD ::模板类实例的元组

Convert std::variant to std::tuple of template class instances

本文关键字:STD 实例 元组 转换      更新时间:2023-10-16

transform_v2t函数在下面的代码中构建模板类A元组A实例:

template <typename T>
struct A
{
    T val;
};
template <class V, template <class> class T, std::size_t... index>
inline constexpr auto transform_v2t(std::index_sequence<index...>)
{
    return std::make_tuple(T<std::variant_alternative_t<index, V>>() ...);
}
template <class V, template <class> class T>
inline constexpr auto transform_v2t()
{
    return transform_v2t<V, T>(std::make_index_sequence<std::variant_size_v<V>>());
}
typedef std::variant<bool, char, int, float, double, std::string> V;
int main()
{
    auto t1 = transform_v2t<V, A>();
}

是否可以将相同的transform_v2t函数应用于具有两个模板参数的类,例如:

template <typename P, typename T>
struct B
{
    P other_val;
    T val;
};

使用P专用为int

使用伪代码,可以是这样的:

template <class T> typedef B<int, T> PartiallySpecializedB;
auto t2 = transform_v2t<V, PartiallySpecializedB>();

请参阅在线示例代码。

切勿在C 11代码中使用typedef,总是更喜欢using(称为别名声明(。

不仅因为您声明的名称在左边(而不是在任何地方(:

using V = std::variant<bool, char, int, float, double, std::string>;

...但是他们也支持别名模板声明:

template <class T> 
using PartiallySpecializedB = B<int, T>;
auto t2 = transform_v2t<V, PartiallySpecializedB>();
相关文章: