Question

Is there a way of using typeid or something similar as a return type in C++?

For example:

I have a private variable in the class, which can be set to any type. How would I be able to return it, as the below does not compile.

#include <type_traits>

typeid(MyVariable) GetValue(){
    return MyVariable;
}
Was it helpful?

Solution

I'd guess the confusion here is about what you mean by "which can be set to any type".

I read that one of four ways:

  1. You have implemented a class like boost::Any and want hide it inside your class returning it's contents when called.
  2. You have a template definition where one of the template parameters provides the type information for MyVariable
  3. You are trying to return the type_info object for the variable defined using a boost::Any analog
  4. You are trying to return the type_info object for the variable defined in a template

If 1 or 3:

template<typename T> T GetValue() { return any_cast<T>(MyVariable); }
const std::type_info &GetValueType() { return MyVariable.type(); }

you haven't provided details of how your boost::Any analog works, so I've just assumed it's a boost::Any instance (which I've personally never used, so let's hope my syntax is correct). This will throw if you try to extract the wrong type from MyVariable. If you prefer to deal with pointers and NULL values do it like this:

template<typename T> T* GetValue() { return any_cast<T*>(&MyVariable); }

This will return a NULL pointer if T is not the type of the item stored in the variable.

If 2 or 4:

Well, in that case you have a template parameter somewhere which defines the type of MyVariable. Something like this is what you want:

template<typename T> class Holder {
    T MyVariable;
    T &GetValue() { return MyVariable; }
    const std::type_info & GetValueType() { return typeid(T); }
};

Well, here's hoping that one of those answers matched the question you were trying to ask :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top