boost::any
uses type erasure to store objects of any type, and you can assign it values of different types at runtime. The any_cast
is used to retrieve the original value, with the correct type, that was stored in the any
object. For instance, your current class allows you to do this
Properties p("int", 42);
std::cout << boost::any_cast<int>(p.value) << '\n';
p = Properties("string", std::string("hello"));
std::cout << boost::any_cast<std::string>(p.value) << '\n';
You cannot just convert the class above into a template and get identical functionality. If you do that, you'll only be able to store a single type of value. And you must change the entire struct
into a template, not just the constructor.
template<typename T>
struct Properties {
public:
Properties() {}
Properties(std::string s, T p)
: name(std::move(s)) // should use initialization list instead
, value(std::move(p)) // of assignment within the body
{}
Properties(T n)
: value(std::move(n))
{}
std::string name;
T value;
};
However, the code I posted above is now illegal.
Properties<int> p("int", 42);
std::cout << p.value << '\n';
// p = Properties<std::string>("string", std::string("hello"));
// will not compile because Properties<int> and Properties<std::string> are
// distinct types
If these restrictions are OK, then the modified definition should work for you.