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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With