将STD ::变体转换为STD ::模板类实例的元组
Convert std::variant to std::tuple of template class instances
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>();
相关文章:
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 通过实例理解std::move及其目的
- 在std::vector上存储带有模板的类实例
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 检查某些类型是否是模板类 std::optional 的实例化
- std::vector 没有重载函数的实例与参数列表匹配
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 比较两个 std::chrono::time_point 实例时出错
- 请参阅在 Visual Studio 2019 中捕获 std::exception 时对函数模板实例化消息的引用
- 在抛出 what() 的实例后调用'std::logic_error'终止:basic_string::_M_construct 空无效
- 抛出实例'std::out_of_range'后调用的终止
- C++如何在类构造函数中实例化 std::array?
- 如何实例化类的公共成员并将其作为 std::p romise 返回?
- 在抛出"std::__cxx11::basic_string<char、std::char_traits<char>、std::分配器<char>>"的实例后调用终
- 在抛出 'std::invalid_argument' 的实例后终止调用 what(): stoi (找不到问题所在)
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?