Search code examples
c++c++11compile-timestatic-assert

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?


Solution

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

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

    Demo here.