0
votes

I am trying to compile this code:

#include <type_traits>
#include <string>
#include <iostream>

enum class mode { str = 1, hello = 0 };

struct foo
 {
  template <typename Enumeration>
  constexpr auto as_integer(Enumeration const value) const
      -> typename std::underlying_type<Enumeration>::type
  {
      return static_cast<typename std::underlying_type<Enumeration>::type>(value);
  }

  template <class... Args>
  constexpr std::string operator()( mode&& first, Args&&... args ) const
   {   
    static_assert( as_integer( first ) == 1 );    
    switch( first )
     {
      case mode::str:
       {
        std::cout << "ok";
       }
      default:
       {
        std::cerr << "Invalid option!"; exit( 0 );
       }
     }
   }
 };

int main()
 {
  foo test;
  test( mode::str, "hi" );
 }

But if I compile with g++ 9.4.0 (C++17 standard) it throws me the following error:

prove.cpp: In member function ‘constexpr std::string foo::operator()(mode&&, Args&& ...) const’:
prove.cpp:19:40: error: non-constant condition for static assertion
   19 |     static_assert( as_integer( first ) == 1 );
      |                    ~~~~~~~~~~~~~~~~~~~~^~~~
prove.cpp:19:40: error: ‘this’ is not a constant expression

It seems that static assertion gives problem, since the expression:

static_assert( as_integer( first ) == 1 );

is not considered constant, but it should be, since this should be the purpose of the as_integer function and I am comparing 1 with 1. What could be the problem? Thanks.

Function parameter like first are not constexpr. - Anoop Rana
Inside of a function, its parameters are never constexpr. Only the function result can be constexpr outside of the function, if the arguments were constexpr. - HolyBlackCat
@AnoopRana how could I solve this by making it constexpr? Could you provide a full answer so I can upvote it? Thanks. - Gianluca Bianco
@HolyBlackCat Could you provide a full example with solution? Thanks. - Gianluca Bianco
if the paramter actually is a constexpr you could make it a template parameter - 463035818_is_not_a_number