Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the type of a variable?

Tags:

c++

types

i want to find out the type of a Variable (the variable is given by a Template parameter, so I don't know what it is).

#include <iostream>
#include <typeinfo>

int main() 
{
    double test;
    std::cout << typeid(test).name() << std::endl;
}

But the Code only emits: $./test

d

but I would need double instead.

The point is, I don't know which type to expect, but I have to write it in a subprogram, which hast to be compiled. So d is a bad idea.

like image 637
cl_progger Avatar asked Nov 23 '11 22:11

cl_progger


Video Answer


2 Answers

If you know the list of types that must be supported, you can write your own function to do this:

template <typename T>
void printtype()
{
  if (typeid(T) == typeid(double))
    std::cout << "double";
  else if (typeid(T) == typeid(int))
    std::cout << "int";
}

Notice that since the function doesn't have an argument of type T, it must always have the type explicitly stated:

printtype<double>()

and of course, the type could be a parameter type:

printtype<U>()
like image 140
John Gordon Avatar answered Sep 18 '22 12:09

John Gordon


In GNU ABI, there is a helper to demangle the name() of a typeid

Disclaimer In case it wasn't obvious, of course the GNU ABI only supports demangling names from the GNU ABI (and probably not even wildly varying versions).

#include <cxxabi.h>
#include <stdlib.h>
#include <string>

template <typename T> std::string nameofType(const T& v)
{
    int     status;
    char   *realname = abi::__cxa_demangle(typeid(v).name(), 0, 0, &status);
    std::string name(realname? realname : "????");
    free(realname);

    return name;
}
like image 42
sehe Avatar answered Sep 21 '22 12:09

sehe