user5767271
user5767271

Reputation:

How to check the type of variable in conditional statement

How can I check the type of a input variable inside if clause in C++? If there is any member function to do this.

Upvotes: 2

Views: 14883

Answers (3)

skypjack
skypjack

Reputation: 50540

An easy to use solution would be the following one:

#include<cassert>

struct B { static int cnt; };
int B::cnt = 0;

template<class T>
struct S: B { static int type; };

template<typename T>
int S<T>::type = B::cnt++;

template<typename T, typename U>
bool f(T, U) {
    return S<T>::type == S<U>::type;
}

int main() {
    assert(f(42, 0));
    assert(!f(0, .0));
}

You can use S<T>::type in a guard statement or wherever you want.
If you have a variable named x, is a matter of using something like:

S<decltype(x)>::type

Upvotes: 0

Peter
Peter

Reputation: 36597

It depends on what type checks you want to do.

The simplest is probably

 #include <typeinfo>     // for the `std::type_info` type

 if (typeid(input_variable) == typeid(chosen_type))
 {
      // input_variable is of type chosen_type
 } 

It is also possible to check the (implementation defined) name strings that identify a type

 if (std::string(typeid(input_variable).name()) == typeid(chosen_type).name())
 {
      // input_variable is of type chosen_type
 } 

The conversion to std::string is needed for comparison operators to work, as the .name() member function returns const char *. Otherwise compare the name() members using strcmp() (either in C's <string.h> or in C++ <cstring> - within namespace std).

Bear in mind that the character sequence returned by typeid(X).name is implementation defined.

In C++11, the type_info type has a hash_code() member, which may also be compared. The values of this are implementation defined, and may vary between executions of the program. Furthermore, as Martin Bonner mentioned in comments, that hash_code() may give false positives for equality (if hash_code()s compare non-equal, the types are different but if they compare equal the types may be different. I mention this, not because I advocate comparing hash_code()s, but because the original question has not explained why comparison of types is desired, so there is no basis to assume a test that might yield false matches is inappropriate.

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

You can try to use:

typeid(yourvariable).name()

You need to include the following header to make it working:

#include <typeinfo>

Upvotes: 2

Related Questions