c++castingc++03

Check if (primitive) types are castable in C++


Is it possible to check (in C++), if types are castable (implicitly or explicitly)? Is there something in the std or is it possible write a function like in C# (C# same Question)?

I want to perform this check on types not the instances of the type.

I'm not sure about the type system in C++. Is there something like the Type class in C# or Java? typeid(int) was the nearest I found. Can I store a type to a variable? Closer reading tips will be appreciated.

At example:

bool isCastable(false);
bool withoutLoss(true);
isCastable = isCastableFromTo(typeid(int), typeid(__int64), withoutLoss); //true
isCastable = isCastableFromTo(typeid(int), typeid(short), withoutLoss); //false
isCastable = isCastableFromTo(typeid(int), typeid(double), withoutLoss); //true
isCastable = isCastableFromTo(typeid(double), typeid(int), withoutLoss); //false
isCastable = isCastableFromTo(typeid(string), typeid(int), withoutLoss); //false

withoutLoss = false;
isCastable = isCastableFromTo(typeid(int), typeid(__int64), withoutLoss); //true
isCastable = isCastableFromTo(typeid(int), typeid(short), withoutLoss); //true
isCastable = isCastableFromTo(typeid(int), typeid(double), withoutLoss); //true
isCastable = isCastableFromTo(typeid(double), typeid(int), withoutLoss); //true
isCastable = isCastableFromTo(typeid(string), typeid(int), withoutLoss); //false

Solution

  • In C++11 you can use std::is_convertible (reference). This checks if an implicit conversion is possible. It does not consider if the conversion would be lossy.


    Example:

    #include <type_traits>
    bool f_to_i = std::is_convertible<float,int>::value; // true
    bool i64_to_i = std::is_convertible<int64_t,int>::value; // true
    bool str_to_i = std::is_convertible<std::string,int>::value; // false