How to store different data types in one list? (C++)

Viewed 56011

I need to store a list of various properties of an object. Property consists of a name and data, which can be of any datatype.

I know I can make a class "Property", and extend it with different PropertySubClasses which only differ with the datatype they are storing, but it does not feel right.

class Property
{
     Property(std::string name);
     virtual ~Property();

     std::string m_name;
};

class PropertyBoolean : Property
{
     PropertyBoolean(std::string name, bool data);

     bool m_data;
};

class PropertyFloat : Property
{
     PropertyFloat(std::string name, float data);

     float m_data;
};

class PropertyVector : Property
{
     PropertyVector(std::string name, std::vector<float> data);

     std::vector<float> m_data;
};

Now I can store all kinds of properties in a

 std::vector<Property*>

and to get the data, I can cast the object to the subclass. Or I can make a pure virtual function to do something with the data inside the function without the need of casting.

Anyways, this does not feel right to create these different kind of subclasses which only differ by the data type they are storing. Is there any other convenient way to achieve similar behavior?

I do not have access to Boost.

8 Answers

Starting with C++ 17 we have something called as std::variant and std::any.

std::variant

An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value.

std::any

The class any describes a type-safe container for single values of any copy constructible type.

  1. An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object. The stored instance is called the contained object. Two states are equivalent if they are either both empty or if both are not empty and if the contained objects are equivalent.
  2. The non-member any_cast functions provide type-safe access to the contained object.
Related