static_assert'ion,long和int是相同的类型

Jon*_*Mee 0 c++ int static-assert long-integer visual-studio-2017

所以我从一个API中获取一个变量,我们将其调用并将其long foo传递给另一个API,将其作为值:int bar.

我在,其中实际上是相同的东西:https://docs.microsoft.com/en-us/cpp/cpp/data-type-ranges?view =

但这会引发:

static_assert(is_same_v<decltype(foo), decltype(bar)>);
Run Code Online (Sandbox Code Playgroud)

因为即使它们实际上是相同的,它们也不是同一类型.对此有一个解决办法,不是用数字界线库匹配等long来的int

Nat*_*ica 7

long并且int是不同的基本类型.即使它们的大小相同,也不是同一类型,所以is_same_v永远不会true.如果您需要,可以检查它们的尺寸是否相同然后继续

static_assert(sizeof(foo) == sizeof(bar));
Run Code Online (Sandbox Code Playgroud)

你甚至可以确保foobar是不可或缺的类型,如

static_assert(sizeof(foo) == sizeof(bar) && 
              std::is_integral_v<decltype(foo)> && 
              std::is_integral_v<decltype(bar)>);
Run Code Online (Sandbox Code Playgroud)

您还可以确保它们具有相同的签名

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)>);
Run Code Online (Sandbox Code Playgroud)