barej
barej

Reputation: 1406

force compiler to reveal type of a variable

I am compiling a rather large project in which I faced with

error: ‘CRoom room’ redeclared as different kind of symbol

Right at

class CRoom
{
.....
} room("test");

The problem is that I searched into the whole my project files and I could not find such a variable anywhere else. Is it possible to force the complier to tell me where it has found the original place of such definition? If it is not possible, at least, is it possible to reveal the type of the original variable at comfile time (Note that this programs has so many other errors and I cannot run it and show variable type. I want the compiler reveals the type for me).

Upvotes: 6

Views: 782

Answers (2)

Praetorian
Praetorian

Reputation: 109239

This can be done easily by declaring a class template and leaving it unimplemented.

template<typename T>
struct dump;

dump<decltype(room)> d;

This will produce the following error messages on gcc and clang respectively

error: aggregate 'dump<CRoom> d' has incomplete type and cannot be defined
error: implicit instantiation of undefined template 'dump<CRoom>'

Live demo

An alternative, that allows the program to compile, is to use Boost.TypeIndex

#include <boost/type_index.hpp>

std::cout << boost::typeindex::type_id_with_cvr<decltype(room)>().pretty_name() << '\n';

This produces the output CRoom on both gcc and clang

Live demo

Upvotes: 8

For getting the compiler to show me the type of something, I usually use an improptu class like this:

template <class T>
struct show_type;

Then, in the code where you need to learn a type, you'd do this:

show_type<decltype(room)> t;

Compile this, and the compiler will rightfully complain that show_type<T> is not defined; but the error message will helpfully spell out the T with which the instantiation was attempted.

Upvotes: 10

Related Questions