In C ++, type conversions are implicitly performed. For example, an object of type int can be assigned const int (as is done in the first lines of the main function in the code below).
Now I want to check the convertibility at runtime that I have a structure in which I can add types, and later I want to check for a given type if one of the types stored in the structure is converted to the given type.
Here is what I came up with so far:
#include <iostream> #include <vector> struct bar { virtual void dummy() {} }; template<typename T> struct foo : public bar { virtual void dummy() {} }; int main() { int i1 = 1; const int i2 = i1; std::vector<bar*> bars; bar* t1 = new foo<int>; bars.push_back(t1); bar* t2 = new foo<int const>; bars.push_back(t2); foo<int const>* t3 = dynamic_cast<foo<int const>*>(bars[0]); std::cout << t3 << std::endl; foo<int const>* t4 = dynamic_cast<foo<int const>*>(bars[1]); std::cout << t4 << std::endl; delete t1; delete t2; return 0; }
To store types in a structure, I created a template structure foo , which is derived from bar . Then I can store different types of int and int const (more precisely, pointing to objects of type foo<int> and foo<int const> ) in the vector bar* s. Then for a given type (here int const ) I check every element in this vector if it can be dynamically added to foo with this type.
When this code is run, t3 becomes nullptr and t4 non-zero pointer. But I wanted to have a non-zero pointer for t3 as well.
I hope it has become clear what I want to do.
Do you have any ideas on how to achieve such a check on the possibility of conversion at runtime (a solution using 11 C ++ functions would be completely fine)?
source share