Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there type trait that show if one type might contain value of other type

Tags:

c++

c++11

c++14

Is there some type trait that checks, if one integral type can hold value of other integral type without data loss?

For example int32_t might hold uint16_t, uint8_t, int32_t, int16_t and int8_t.

However int32_t can not hold uint32_t, nor uint64_t or int64_t.

Update

I made naive solution and I am posting it as answer. I know one can use std::is_same but I think this way is more expressive.

like image 908
Nick Avatar asked Nov 01 '17 10:11

Nick


1 Answers

We can take advantage of the existing language rules here.

For list-initialization, narrowing conversions are ill-formed. We are trying to detect narrowing conversions. Hence, to the void_t!

template <class X, class Y, class = void>
struct can_hold : std::false_type { };

template <class X, class Y>
struct can_hold<X, Y,
    void_t<decltype(X{std::declval<Y>()})>>
: std::true_type { };
like image 191
Barry Avatar answered Nov 16 '22 02:11

Barry