gpt4 book ai didi

c++ - 如果 compile-time-constant 参数错误,则生成编译时错误

转载 作者:太空狗 更新时间:2023-10-29 23:43:43 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,如果使用编译时常量参数调用它,如果参数的值与 static_assert 不匹配,它将触发编译时错误,但是仍然可以在运行时使用计算值调用。

有点像这样:

template<int N> void f(N){
static_assert(N == 5, "N can only be 5.");
do_something_with(N);
}

void f(int N){
if(N == 5){
do_something_with(N);
}
}

volatile int five = 5;
volatile int six = 6;

int main() {
f(5); //ok
f(6); //compile-time error
f(five); //ok
f(six); //run-time abort

return 0;
}

我该怎么做?

此外,如果可能的话,我希望能够保留简单的 f(something) 语法,因为这段代码是为一个库设计的,不熟悉的初学者应该可以使用它使用模板语法。

最佳答案

我能想到的最好的是一个抛出异常的 constexpr 函数。

如果在编译时执行,throw 会导致编译错误;如果在运行时执行,则抛出异常

有点像

#include <stdexcept>

constexpr int checkGreaterThanZero (int val)
{ return val > 0 ? val : throw std::domain_error("!"); }

int main()
{
// constexpr int ic { checkGreaterThanZero(-1) }; // compile error

int ir { checkGreaterThanZero(-1) }; // runtime error
}

-- 编辑 --

正如 yuri kilocheck 所指出的,您可以调用 std::abort() 而不是抛出异常;举例说明

constexpr int checkGreaterThanZero (int val)
{ return val > 0 ? val : (std::abort(), 0); }

关于c++ - 如果 compile-time-constant 参数错误,则生成编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com