繁体   English   中英

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

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

我有一个Assert函数,用于评估断言:

  • 如果先决条件在运行时失败,此函数将输出错误消息并终止程序。

  • 如果先决条件在常量表达式中失败,则会导致编译时错误。

我希望当断言在常量评估表达式中失败时,此函数也会生成编译时错误:

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

我想过使用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);
    }

我只使用 GCC,我一直在寻找一个会导致编译时错误的内置函数,这将是一个 constexpr 但没有找到。

是否有任何技巧可以在表达式中获得可以被常量评估的编译时错误?

您可以调用未在任何地方定义的函数以导致编译时错误。 或者,由于您无论如何都在使用 gcc,因此您可以从常量部分内部调用属性错误函数,从而在编译此单元期间导致编译时错误。 要使其工作,您必须在启用优化的情况下进行编译。

我看到使用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);
}

我曾经用 CI 编写了一个名为curb的库,它可以做这样的事情。

暂无
暂无

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

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