Question

I'd like a variant contain copies of objects of its type. Somehow it is not working:

struct value
{
};

class json;

using json = ::boost::variant<
  ::std::vector<::std::unique_ptr<json> >,
  ::std::unordered_map<::std::string, ::std::unique_ptr<json> >,
  value
>;

json.hpp:116:2: error: conflicting declaration 'using json = '
 >;
  ^
json.hpp:110:7: error: 'class json' has a previous declaration as 'class json'
 class json;

I know of 2 workarounds already: ::std::unique_ptr<void>, with a custom deleter, as well as the possibility of using ::boost::any instead of the variant, but are these the only ways? The problem with ::boost::any is that I need to enable RTTI for it to work.

Was it helpful?

Solution

What about:

struct json : ::boost::variant<
  ::std::vector<::std::unique_ptr<json> >,
  ::std::unordered_map<::std::string, ::std::unique_ptr<json> >,
  value
>
{
  using variant::variant;

  template <typename U>
  json& operator=(U&& u)
  {
    variant::operator=(::std::forward<U>(u));

    return *this;
  }
};

That would be the solution, except it doesn't work for me with g++ (constructing json out of vector fails because of ambiguous constructor call). Construction from a const reference to such a vector works, but not not from a non-const reference. I have no idea why. In addition, unique_ptr doesn't work with boost::variant for me because it's uncopyable (shared_ptr does work).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top