URL87
URL87

Reputation: 11032

Get the type which a template class consist of

Having -

C_Type.h

#ifndef C_TYPE_H
#define C_TYPE_H
template <class T>
class C_Type {
    public:
        T m_val;
            // implementation ... 

};

#endif

And a program -

#include <iostream>
#include <typeinfo>
#include "C_Type.h"
using namespace std ; 


int main () {
    C_Type<int> a  ; 
    cout <<typeid(a.m_val).name()<<endl;

}

I trying to extract the int which C_Type<int> consist of , the above program just gave output - i .

Edit :

Is it possible to get the type (i.e int or i) with no regards to the class members (i.e m_val) ?

Upvotes: 3

Views: 102

Answers (4)

pmr
pmr

Reputation: 59841

The name returned by typeid::name is compiler specific and for some compiler it is something horrible (like i for int). Most compilers support demangling of names which leads to a nicer representation, but still is useless for programmatic use.

Here is a list of demangling APIs for common compilers:

Upvotes: 5

If you need to retrieve the template parameter from a template specification (and you have C++11), you can do this:

template <template <typename> class Templ, typename T>
T typeGetter(Templ<T>);

Then, in your main:

int main () {
    C_Type<int> a;
    decltype(typeGetter(a)) i = 7; //declares i to be int
}

Upvotes: 0

James Kanze
James Kanze

Reputation: 154047

In response to your last question (concerning getting the type without referring to a member): no. In the standard library, there is a convention to provide typedef for the instantiation type and the types derived from it; the usual name is value_type, but there are exceptions (e.g. std::map). If you want to adhere to this convention (which isn't a bad idea), you should add:

typedef T value_type;

to your class (as a public member), and refer to it when you want the type, rather than some arbitrary member (which may or may not be present).

Upvotes: 3

Vitali
Vitali

Reputation: 11

"i" is the correct name may be of the type "int"? it's just a name! What do you want to do with the name?

 int main () {
    C_Type<int> a  ; 
    int test=0;
    if(typeid(a.m_val) == typeid(test))
      cout <<"Int"<<endl;
 }

Upvotes: 1

Related Questions