I would like to be able to create a variant that contains a std::map<std::string, MyVariant>
as one of its cases. The ideal would be able to write something like
using MyVariant = std::variant<int, std::string, std::map<std::string, MyVariant>>;
but this requires forward declaration.
I'm aware that similar questions have been asked previously, e.g. here and here, but these have mainly been focused on the case of std::vector
, and since C++17 std::vector
is allowed to use incomplete types, while std::map
does not.
In particular, I'm wondering if the fixed-point combinator solution in this answer would work in this case? Adapting the code from that 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>;
However if there's another way to do it, I would be interested with that also.