Search code examples
c++visual-studio-2017intlong-integerstatic-assert

static_assert'ion that a long and int are the Same Type


So I'm taking a variable from one API, we'll call it long foo and passing it to another API which takes it as the value: int bar.

I'm in in which these are effectively the same thing: https://learn.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=vs-2017

But this will fire:

static_assert(is_same_v<decltype(foo), decltype(bar)>);

Because even though these are effectively the same, they are not the same type. Is there a workaround for this, other than using the numeric limits library to match a long to an int?


Solution

  • long and int are different fundamental types. Even if they are the same size they are not the same type, so is_same_v will never be true. If you want you can check their sizes are the same then proceed with

    static_assert(sizeof(foo) == sizeof(bar));
    

    You can even make sure that foo and bar are integral types like

    static_assert(sizeof(foo) == sizeof(bar) && 
                  std::is_integral_v<decltype(foo)> && 
                  std::is_integral_v<decltype(bar)>);
    

    You can also make sure they have the same signedness like

    static_assert(sizeof(foo) == sizeof(bar) && 
                 std::is_integral_v<decltype(foo)> && 
                 std::is_integral_v<decltype(bar)> &&
                 std::is_signed_v<decltype(foo)> == std::is_signed_v<decltype(bar)>);