hochl hochl - 2 months ago 6
C++ Question

Get type of expression at compile time

While programming with the

auto
keyword it would sometimes be convenient to know the type that is used by the compiler at compile time. It does not matter if the compilation aborts where I need to know the type. Simple example:

std::vector< int > s{1, 2, 3};

for (auto elem : s) {
elem = 5;
}

for (auto elem : s) {
std::cout << elem << std::endl;
}


will print

1
2
3


because elem is of type
int
, not
int&
. It would be nice to try compile the code and get the type of
elem
to catch such mistakes early.

Answer

Classical way is to declare template structure without definition:

template <typename> struct Debug;

and then use it:

template struct Debug<std::string>;

or

for (auto elem : s) {
    Debug<decltype(elem)>{};

    elem = 5;
}

Message error looks like

error: explicit instantiation of 'struct Debug<std::__cxx11::basic_string<char> >' before definition of template
 template struct Debug<std::string>;
                 ^~~~~~~~~~~~~~~~~~

error: invalid use of incomplete type 'struct Debug<int>'
         Debug<decltype(e)>{};

Demo

BTW, now some IDEs show the type when mouse is over auto or the variable.

Comments