I have 2 structs which hold different data and each one has a method to serialize this data into a JSON string:
struct Struct1
{
Struct1(int value) : value(value){};
int value;
std::string ToJSON() const
{
std::string ret = "{value: " + std::to_string(value) + "}";
return ret;
}
};
struct Struct2
{
Struct2(std::string id, std::string image, std::string name) : id(id), image(image), name(name){};
std::string id;
std::string image;
std::string name;
std::string ToJSON() const
{
return "{id: " + id + " image: " + image + " name: " + name + "}";
}
};
I need to store several of them in one container in order to iterate over them later and get the JSON string from each object. I do this using a std::variant
.
std::vector<std::variant<Struct1, Struct2>> v3;
I can then iterate over the container like this:
auto GetJSONString = [](auto&& _in){return _in.ToJSON();};
for (const auto& nextV : v3)
{
auto test = std::visit(GetJSONString, nextV);
std::cout << test << " ";
}
std::cout << std::endl;
Everything is working fine until I try to use braced-init-lists to fill the vector.
In other words, this is working:
std::vector<std::variant<Struct1, Struct2>> v{Struct1(5), Struct2("someid", "someimage", "somename")};
But this not:
std::vector<std::variant<Struct1, Struct2>> v4{ {13}, {"someid", "someimage", "somename"}};
On the not working code I get the following compiler error:
error: no matching function for call to 'std::vector<std::variant<Struct2, Struct1> >::vector(<brace-enclosed initializer list>)
I do not understand why is this. Can't I use brace initialization in this case? If so,... why? Or do I need to modify my structs in some way that they support this kind of initialization?
Here is a minimal working example on wandbox.org to further illustrate my problem.