相关疑难解决方法(0)

有可能知道constexpr什么时候真的是constexpr?

由于constexpr的扩展版本(我想从C++ 14开始),你可以声明constexpr函数,它们可以用作"真正的"constexpr,即代码在编译时执行或者可以表现为内联函数.那么什么时候可以有这个程序:

#include <iostream>

constexpr int foo(const int s) {
  return s + 4;
}

int main()
{
    std::cout << foo(3) << std::endl;
    const int bar = 3;
    std::cout << foo(bar) << std::endl;
    constexpr int a = 3;
    std::cout << foo(a) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当然,结果是:

7
7
7
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.所以我的问题是:如果函数在编译时或运行时执行,有没有办法(可能是标准的)知道foo(const int s)?

编辑:也可以在运行时知道在编译时是否评估了函数?

c++ constexpr c++14 c++17

21
推荐指数
5
解决办法
2800
查看次数

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

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

  • 如果前提条件在运行时失败,该函数将输出一条错误消息并终止程序。

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

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

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

我考虑过使用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);
    }
Run Code Online (Sandbox Code Playgroud)

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

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

c++ gcc assertion constant-expression c++20

4
推荐指数
1
解决办法
842
查看次数

标签 统计

c++ ×2

assertion ×1

c++14 ×1

c++17 ×1

c++20 ×1

constant-expression ×1

constexpr ×1

gcc ×1