0

Is there a statement s_type which allows to determine the type of an object in C++?

E.g.

s_type(int a);      // int
s_type(&a);         // int*

2 Answers2

1

It's called decltype:

int a = 0;
decltype(a) b = 42;
bipll
  • 11,747
  • 1
  • 18
  • 32
1
#include <boost/type_index.hpp>
#include <iostream>

int main() {
  using boost::typeindex::type_id_with_cvr;
  using std::cout;

  int a = 42;
  int& b = a;
  int* c = &a;

  cout << type_id_with_cvr<decltype(a)>().pretty_name() << '\n';
  cout << type_id_with_cvr<decltype(b)>().pretty_name() << '\n';
  cout << type_id_with_cvr<decltype(c)>().pretty_name() << '\n';
}

Output is:

int  
int&  
int*  

If I want to see the types, this is the method I use. It does require boost and some people don't like to see third-party libraries, but this does the job much better than C++'s typeid.

sweenish
  • 4,793
  • 3
  • 12
  • 23