I am not sure if my answer will help.
Short answer: you do not need / do not need to know the type of the variable in order to use it.
If you need to give the type of a static variable, then you can just use auto.
In the more complex case, when you want to use "auto" in a class or structure, I would suggest using a template with decltype.
For example, suppose you use a foreign library that has an unknown_var variable in it, and you want to put it in a vector or structure, you can do this completely:
template <typename T> struct my_struct { int some_field; T my_data; }; vector<decltype(unknown_var)> complex_vector; vector<my_struct<decltype(unknown_var)> > simple_vector
Hope this helps.
EDIT: For convenience, here is the most difficult case I can think of: having a global variable of unknown type. In this case, you will need C ++ 14 and a template variable.
Something like that:
template<typename T> vector<T> global_var; void random_func (auto unknown_var) { global_var<decltype(unknown_var)>.push_back(unknown_var); }
It's still a little tedious, but it's as close as you can get to typical languages. Just make sure that when you reference a template variable, always put the template specification there.
gohongyi Jan 03 '18 at 4:03 2018-01-03 04:03
source share