I would like to know if it’d be possible (and if, how) to create a pointer of X value
Now, let’s say I know which types would be possible to be assigned in this pointer.
For example, a pointer of X value (of course feel free to change the name of this value), that’d be able to point to variables of string, bool and a custom class
Usually what you describe is a bad idea.
void*works, for marginal values of works. It throws out all type safety, requiring you to keep track of it.Creating a root type sort of works, but it doesn’t work for primitive types, and is rather intrusive.
A
boost::variant< bool*, std::string*, MyClass* >is a variable that can contain a pointer to any one of these 3 types (bool,std::stringorMyClass). You will probably find it challenging to use, because it enforces type safety, and the syntax can get annoying.Similarly, a pointer to
boost::variant< bool, std::string, MyClass >may be what you want, but it doesn’t let you point toboolvariables you aren’t fooling around with.With full C++11 support,
unioncan contain arbitrary types, together with an enum can let you do something very much like aboost::variant. As a downside, this requires the thing you be pointed to be aunion. With or without full C++11 support, a union of pointers is reasonable. In both cases, you’ll have to track the type manually and keep it in sync.What you really need to think about is “why am I asking this?”, because as with many questions, the motivation matters. You may not be asking the right question.