is this a good use case for std::any?

Apr 13, 2020 at 8:53pm
Hi

I am writing a class which will have different members e.g.

1
2
3
4
class x{
std::string nm;
unsigned int id;
}


However, I am aware that users of the class may wish to store their own custom data in an object instantiating the class e.g.

 
std::string date_of_birth;


I think one way of doing this is by using std::any:

1
2
3
4
5
6
7
8
9
10
class x{
std::string nm;
unsigned int id;
std::any custom_data;

void setCustomData(std::any anything) {
  custom_data = anything;
}

};


Is this a good use case for std::any? Are there any other options I should be considering? I assume that the user could instead inherit from my class but this does seem overkill to simply store extra data.

One problem is that I had wanted to save the data in the class to an XML file. I assume that it won't be possible to save the std::any variable to an XML file.

Thanks

Apr 13, 2020 at 9:48pm
This isn't really a good use for std::any. Handling their custom data will be very difficult. Is it a string? Is it a number? Is it a bool? You don't know, and it's very hard to see how it would be helpful to the program.

You can always do this, but it'll be a pain, and you can't predict how the user will want this information used to create logical functions for it.
Topic archived. No new replies allowed.