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;
}
The typeid operator returns an lvalue of type const std::type_info that represents the type of expression expr. You must include the standard template library header <typeinfo> to use the typeid operator. Classes A and B are polymorphic; classes C and D are not.
The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
typeid is an operator in C++. It is used where the dynamic type or runtime type information of an object is needed. It is included in the <typeinfo> library. Hence inorder to use typeid, this library should be included in the program. The typeid expression is an lvalue expression.
To use the typeid operator in a program, one needs to include the library header <typeinfo>. It returns the lvalue of type const type_info to represent the type of value. Expression of typeid is an lvalue expression (lvalue has the address which is accessible by the program.
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:
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With