C ++ 11 - static_assert在constexpr函数中? [英] C++11 - static_assert within constexpr function?
问题描述
如何在 constexpr
函数中正确执行 static_assert
例如:
constexpr int do_something(int x)
{
static_assert(x& x must be> 0);
return x + 5;
}
这不是有效的C ++ 11代码,因为constexpr函数必须包含返回语句。我不认为标准有一个例外,虽然,GCC 4.7不允许我编译这段代码。
< blockquote>
这是无效的C ++ 11代码,因为constexpr函数只能包含一个return语句。
这不正确。在 constexpr
函数中的 static_assert
什么是不是很好在常量表达式中使用函数参数,就像你这样做。
您可以抛出 x <= 0
。在需要常量表达式的上下文中调用该函数将无法编译
constexpr int do_something(int x){
return x> 0? (x + 5):(throw std :: logic_error(x must be> 0));
}
How would one properly do a static_assert
within a constexpr
function? For example:
constexpr int do_something(int x)
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
This is not valid C++11 code, because a constexpr function must only contain a return statement. I don't think that the standard has an exception to this, although, the GCC 4.7 does not let me compile this code.
This is not valid C++11 code, because a constexpr function must only contain a return statement.
This is incorrect. static_assert
in a constexpr
function are fine. What is not fine is using function parameters in constant expressions, like you do it.
You could throw if x <= 0
. Calling the function in a context that requires a constant expression will then fail to compile
constexpr int do_something(int x) {
return x > 0 ? (x + 5) : (throw std::logic_error("x must be > 0"));
}
这篇关于C ++ 11 - static_assert在constexpr函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!