Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I confirm an assumption of an automatically inferenced type at compile time? (i.e. static_assert style

Occasionally, I'll assign the returned value of a function to a variable of auto type (e.g. auto returnValue = someFunction();), but still would like to clarify/enforce certain assumptions about the type of that variable - i.e. That it is of type int.

While Concepts & type_traits provide some very powerful static assumption-verifying features, they don't enable something like this:

static_assert( isType( returnValue, int ) );
//OR
static_assert( int == typeof( returnValue ) );

How can I do this?

like image 892
Alexander Riccio Avatar asked Jan 30 '26 14:01

Alexander Riccio


1 Answers

You can use type traits ie std::is_same here :

static_assert( std::is_same<int, decltype( returnValue ) >:: value  ,  "Error, Bad Type");

Demo here.

like image 137
quantdev Avatar answered Feb 02 '26 03:02

quantdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!