C++ 是一种静态类型的语言。因此,所有变量的类型都需要在编译时知道(并且不能改变)。您需要一个依赖于运行时值的类型。幸运的是,C++ 还具有对象的动态类型。
警告:此答案中的所有代码仅用于演示基本概念/想法。它缺少任何类型的错误处理、理智的接口(构造函数……)、异常安全……。所以不要用于生产,考虑使用 boost 提供的实现。
要使用此功能,您需要所谓的多态基类:一个具有(至少)一个virtual 成员函数的类,您可以从中派生更多类。
struct value_base {
// you want to be able to make copies
virtual std::unique_ptr<value_base> copy_me() const = 0;
virtual ~value_base () {}
};
template<typename Value_Type>
struct value_of : value_base {
Value_Type value;
std::unique_ptr<value_base> copy_me() const {
return new value_of {value};
}
};
然后,您可以拥有一个静态类型的指针或对该基类的引用的变量,该变量可以指向/引用来自基类以及任何派生类的对象。如果您有明确定义的接口,则将其编码为虚拟成员函数(想想Shape 和area ()、name ()、...函数)并通过该基类指针进行调用/参考(as shown in the other answer)。否则使用(隐藏的)动态强制转换来获得具有动态类型的静态类型的指针/引用:
struct any {
std:: unique_ptr<value_base> value_container;
// Add constructor
any(any const & a)
: value_container (a.value_container->copy_me ())
{}
// Move constructor
template<typename T>
T & get() {
value_of<T> * typed_container
= dynamic_cast<value_of<T> *>(value_container.get();)
if (typed_container == nullptr) {
// Stores another type, handle failure
}
return typed_container->value;
}
// T const & get() const;
// with same content as above
};
template<typename T, typename... Args>
any make_any (Args... && args) {
// Raw new, not good, add proper exception handling like make_unique (C++14?)
return {new T(std:: forward<Args>(args)...)};
}
由于对象构造是在运行时完成的,因此指向/引用对象的实际类型可能取决于运行时值:
template<typename T>
any read_and_construct (std:: istream & in) {
T value;
// Add error handling please
in >> value;
return make_any<T>(std:: move (value));
}
// ...
// missing: way of error handling
std::map<int, std:: function<any(std:: istream &)>> construction_map;
construction_map.insert(std::make_pair(1, read_and_construct<double>));
// and more
int integer_encoded_type;
// error handling please
cin >> integer_encoded_type;
// error handling please
any value = construction_map [integer_encoded_type] (cin);
您可能已经注意到,上面的代码也使用了一个明确定义的构造接口。 如果您不打算对返回的 any 对象做很多不同的事情,可能会在程序运行的大部分时间将它们存储在各种数据结构中,那么 使用 any 类型很可能是矫枉过正,您也应该将依赖于类型的代码放入这些构造函数中。
这种any 类的一个严重缺点是它的通用性:可以在其中存储几乎任何类型。这意味着(实际)存储对象的(最大)大小在编译期间是未知的,因此无法使用具有自动持续时间(“堆栈”)的存储(在标准 C++ 中)。这可能会导致使用动态内存(“堆”)的代价高昂,这比自动内存相当慢。每当必须制作许多 any 对象的副本时,此问题就会出现,但如果您只是保留它们的集合,则可能无关紧要(缓存位置除外)。
因此,如果您在编译时知道必须能够存储的类型集,那么您可以(在编译时)计算所需的最大大小,使用它的静态数组大小并在该数组中构造对象(从 C++11 开始,您也可以使用(递归模板)union 实现相同的目的):
constexpr size_t max_two (size_t a, size_t b) {
return (a > b) ? a : b;
}
template<size_t size, size_t... sizes>
constexpr size_t max_of() {
return max_two (size, max_of<sizes>());
}
template<typename... Types>
struct variant {
alignas(value_of<Types>...) char buffer[max_of<sizeof (value_of<Types>)...>()];
value_base * active;
// Construct an empty variant
variant () : active (nullptr)
{}
// Copy and move constructor still missing!
~variant() {
if (active) {
active->~value_base ();
}
}
template<typename T, typename... Args>
void emplace (Args... && args) {
if (active) {
active->~value_base ();
}
active = new (buffer) T(std:: forward<Args>(args)...);
}
};