Quantcast
Viewing all articles
Browse latest Browse all 22009

How to get a compile time error in constant evaluated expression?

I have an Assert function that I use to evaluate assertion:

  • if the precondition fails at runtime, this function will output an error message and it will terminate the program.

  • if the precondition fails inside a constant expression, it will cause a compile time error.

I would like that this function also generates a compile time error when the assertion fails in constant evaluated expression:

const int a = (Assert(false),0); //generate a runtime error 
                                 //=> I would like it generates a compile time error

I thought about using std::is_constant_evaluated: compiler-explorer

#include <type_traits>

using namespace std;

void runtime_error();

constexpr void compile_time_error(){} //should generates a compile time error

constexpr void Assert(bool value){
   if (value) return;
   if (is_constant_evaluated())
     compile_time_error();
   else
     runtime_error();
   }

void func(){
    const int a = (Assert(false),0);
    }

I only use GCC, I have look for a builtin function that would cause a compile time error and that would be a constexpr but did not find one.

Is there any trick to get a compile time error in expression that could be constant evaluated?


Viewing all articles
Browse latest Browse all 22009

Trending Articles