简体   繁体   English

如何在常量评估表达式中获得编译时错误?

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

I have an Assert function that I use to evaluate assertion:我有一个Assert函数,用于评估断言:

  • 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我想过使用std::is_constant_evaluatedcompiler-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.我只使用 GCC,我一直在寻找一个会导致编译时错误的内置函数,这将是一个 constexpr 但没有找到。

Is there any trick to get a compile time error in expression that could be constant evaluated?是否有任何技巧可以在表达式中获得可以被常量评估的编译时错误?

You can call a function that is nowhere defined to cause a compile time error.您可以调用未在任何地方定义的函数以导致编译时错误。 Or, since you are using gcc anyway, you can call a attribute error function from inside the constant part to cause a compile time error during compilation of this unit.或者,由于您无论如何都在使用 gcc,因此您可以从常量部分内部调用属性错误函数,从而在编译此单元期间导致编译时错误。 To make it work, you have to compile with optimizations enabled.要使其工作,您必须在启用优化的情况下进行编译。

I see that with std::is_constant_expression it does not work in gcc 9.2, but I managed it to work with __builtin_constant_p .我看到使用std::is_constant_expression它在 gcc 9.2 中不起作用,但我设法将它与__builtin_constant_p

#include <type_traits>

constexpr void Assert(bool value) {
   if (__builtin_constant_p(value)) {
        if (!value) {
            extern __attribute__(( __error__ ( "error" ) ))
            void compile_time_error(void);
            compile_time_error();
        }
    } else {
        if (!value) {
            void runtime_error();
            runtime_error();
        }
   }
}

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

I have once written a library in CI called curb that would do something like this.我曾经用 CI 编写了一个名为curb的库,它可以做这样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM