I wish get rid of boost dependency on my code. I have the following struct construct. When calling and using this struct at another place in the code boost::any_cast>
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(p.value) << '\n';
p = Properties("string", std::string("hello"));
std::cout << boost::any_cast(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
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 p("int", 42);
std::cout << p.value << '\n';
// p = Properties("string", std::string("hello"));
// will not compile because Properties and Properties are
// distinct types
If these restrictions are OK, then the modified definition should work for you.