继承TypeBase。运行时尝试从TypeBase到Type<T>的dynamic_cast能不能成功,就能运行时知道里面存的是不是...
然而,如果编译器不支持RTTI,就无法使用dynamic_cast或typeid等运算符来检查std::any中存储的类型。 在这种情况下,可以通过其他方式来检查std::any的类型。一种常见的方法是使用type_index类,它可以用来比较类型信息。可以通过std::any的type()成员函数获取存储的类型信息,并将其与目标类型的type_index进行比较,以...
template <typename T> Tany_cast(){autop = dynamic_cast<Data<T>*>(base.get());if(!p) throw"type is error\n";returnp->value; } private:classBase{public: virtual ~Base() {}// 基类是一个多态类,必须定义析构函数}; template <typename T>classData:public Base { public: Data(T t) :...
CEO* getCEO() const { return ceo; } Worker* getManager (int a = 0) { return ceo->getManager(a); } Worker* getSupervisor (int a = 0, int b = 0) { return dynamic_cast(ceo->getManager(a))->getSupervisor(b); } Worker* getDishwasher (int a = 0, int b = 0, int c = 0...
std::any a = 1;if (a.type() == typeid(int)) {int value = std::any_cast<int>(a);std::cout << value << std::endl;} 在英语中,我们通常会说"std::any provides a member function named type to query the type of its stored value, and a template function named any_cast to cast...
cout << std::any_cast<const std::string&>(a) << "\n"; //hello // --- prints "Wrong Type!" below --- try { std::cout << std::any_cast<double>(a) << "\n"; }catch(const std::bad_any_cast&) { std::cout << "Wrong Type!\n"; } //Pointer cast example // ---...
2)The non-memberany_castfunctions provide type-safe access to the contained object. Implementations are encouraged to avoid dynamic allocations for small objects, but such an optimization may only be applied to types for whichstd::is_nothrow_move_constructiblereturnstrue. ...
2)Ifotheris empty, the constructed object is empty. Otherwise, equivalent toany(std::in_place_type<T>,std::any_cast<constT&>(other)), whereTis the type of the object contained inother. 3)Ifotheris empty, the constructed object is empty. Otherwise, the constructed object contains either...
assert(false); // never runs: any_cast returns nullptr since // a1 doesn't contain a string } The C++ Standard encourages implementations to store small objects with non-throwing move constructors directly in the storage of theanyobject, avoiding the costs of dynamic allocation. This feature ...
assert(false); // never runs: any_cast returns nullptr since // a1 doesn't contain a string } The C++ Standard encourages implementations to store small objects with non-throwing move constructors directly in the storage of theanyobject, avoiding the costs of dynamic allocation. This feature ...