boost::any
使用类型擦除来存储任何类型的对象,您可以在运行时为其分配不同类型的值。any_cast
用于检索存储在any
对象中的具有正确类型的原始值。例如,您当前的课程允许您这样做
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';
您不能只是将上面的类转换为模板并获得相同的功能。如果这样做,您将只能存储一种类型的值。而且你必须把整个struct
变成一个模板,而不仅仅是构造函数。
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;
};
但是,我上面发布的代码现在是非法的。
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
如果这些限制没问题,那么修改后的定义应该适合您。