2

Is there a way to get std::type_info from the type's name? For example,

std::type_info f(std::string name) {
std::type_info info; 
...
return info;
}

int main() {
const std::string name = typeid(double).name();
std::type_info info = f(name);
assert(info==typeid(double));
}

What would the function f be?

Engineero
  • 12,340
  • 5
  • 53
  • 75
ad_ad
  • 375
  • 3
  • 14
  • 1
    I suspect this is not possible, but I can't come up with a convincing reason why it wouldn't be, other than I don't know of a function that does a reverse-lookup on this information.... – Xirema Nov 17 '17 at 20:45
  • @Xirema: There can be no reverse lookup if the name isn't guaranteed to be different for different types. – Christian Hackl Nov 17 '17 at 20:50
  • Though you might want to use type_info elsewhere, using ````std::is_same```` is a much better approach of comparing types. – mascoj Nov 17 '17 at 20:51
  • Related: https://stackoverflow.com/questions/28861760/what-is-the-actual-purpose-of-stdtype-infoname – user0042 Nov 17 '17 at 20:54

1 Answers1

8

No. As documentation for std::type_info::name says:

No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.

I don't know your exact use case, but chances are you can utilise C++11 std::type_index instead.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62