let's suppose I have program like the one below, is it possible to make a single "get" function to retrieve any of the used variables in union using templates or something else?
Sorry, but there is noway a function can have multiple return value types. Template has nothing to do with it. But good news : All of your members can be converted into a universal int, if you wish. Only thing your double member will truncated before it can return as a return value.
That said, template is a very good idea. But you often need to at least give a compiler a hint (especially in your case) in order to be able to use them. Talking about without giving a compiler a hint. A compiler can only know the appropriate return value type for each situation during its compile time if a hint is specified. Then you are fine, but if you just call your get function the universal way (classes[i].get()) and expect your program to predict the appropriate return value type at run-time, well your member type may change during your program's run-time, being outside what a complier can offer to help. Compilers do nothing to help you with your program's run-time excepting for debugging. Your function cannot adapt to return a proper return value type during its execution when you need it the most, and well that's it.
However, there's still hope. Another way for you : make operator functions (because they can be overloaded)
I actually made operator functions but still would somehow prefer to do it with templates, as I found several threads on stackoverflow saying that it's possible but (in that specific case) useless, or messy, or something like that (and I never used templates before, so this might actually teach me something, if possible)
well my get function would kinda know what to return, as there's the "type" variable that stores what my class holds...
so is something like this possible?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//within class
template<typename T>
T get();
template<typename T>
T myclass::get()
{
if(type == TYPE_INT)
//return int
elseif(type == TYPE_LONG)
//return long
elseif(type == TYPE_DOUBLE)
//return double
elseif(type == TYPE_STRING)
//return c
}
what is that get_value function? I seem to not be able to find it anywhere, is it custom made? what is it supposed to do? convert any of the values I'll be using to string? something like
store them in the variable of specific type (int, long, double, char...) as mentioned above, the thread 5a8Ym39o6 posted looks fine so far so I'll try to implement that