I'm not sure this is possible, but is there a way, using template programming magic, to define a function that has different return values depending on what input it takes?
Potentially:
template<typename resultType>
resultType GetResult(const std::string &key); // where the value of key may change resultType
template<typename keyType, typename resultType>
resultType GetResult(keyType key);
Now, I know that the above isn't correct. To use the first one, you'd have to know what resultType
was before calling the function. However, I've learned that a lot of "impossible" things are often made possible with just another layer (or two) of indirection. I just can't seem to find the right way to do it.
The second option tickles my brain though. I feel like I should be able to define some other helper object that maps strings to types (or whatever) and then the compile-time result of that will call GetResult
with the appropriate template parameter.
Edit: Assume that the types used for resultType
are unrelated. There is not an interface that can be tested for the "real" type (maybe it could be an int
and a MyClass *
).
Edit 2: The real-world usage is that I've got a third-party object that contains a collection of Widgets, Gadgets, etc. You can ask for these by string id (prefixed with a type, conveniently), but you have to parse the string to find out that you need to call "collectionInstance.getWidget(id)". My plan was to write a thin wrapper object that would intelligently know how to get at these internal objects.