【发布时间】:2021-12-29 13:45:14
【问题描述】:
我希望能够创建一个包含std::map<std::string, MyVariant> 作为其案例之一的变体。理想的情况是能够写出类似的东西
using MyVariant = std::variant<int, std::string, std::map<std::string, MyVariant>>;
但这需要前向声明。
我知道以前有人问过类似的问题,例如here 和 here,但这些主要集中在 std::vector 的情况下,并且由于 C++17 允许 std::vector 使用不完整类型,而 std::map 不允许使用。
特别是,我想知道this answer 中的定点组合器解决方案是否适用于这种情况?根据该答案改编代码:
#include <map>
#include <string>
#include <variant>
// non-recursive definition
template<typename T>
using VariantImpl = std::variant<int, std::string, std::map<std::string, T>>;
// fixed-point combinator
template<template<typename> typename K>
struct FixCombinator : K<FixCombinator<K>>
{
using K<FixCombinator>::K;
};
using MyVariant = FixCombinator<VariantImpl>;
但是,如果有其他方法可以做到这一点,我也会对此感兴趣。
【问题讨论】:
-
你用的是什么编译器? this compiles
-
@KamilCuk - 我想避免未定义的行为。不幸的是,在某些编译器上成功编译并不能保证这一点。
标签: c++ c++17 self-reference std-variant