问题描述
我有一个constexpr函数看起来像这样: constexpr int foo(int bar)
{
static_assert(bar> arbitrary_number,请使用较低的数字);
return something_const;但是,使用GCC 4.6.3编译这段代码时总是告诉我。
错误:'bar'不能出现在常量表达式中
我尝试过类似
constexpr int foo(constexpr const int bar)
{
static_assert(bar> arbitrary_number,Use a lower number please
return something_const;
}
但是constexpr不能用于函数参数。
有一些简单的方法告诉编译器bar总是一个编译时常数?
解决方案如果 bar
始终是编译时常量,则应将函数写为:
template< int bar>
constexpr int foo()
{
static_assert(bar> arbitrary_number,请使用较低的数字);
return something_const;
}
因为如果你不这样做,已经写入,则在这种情况下,可以使用非const 参数调用函数它只是当你传递非const参数,那么函数将丢失它的constexpr - 性。
请注意,在上面的代码 arbitrary_number
也应该是常量表达式,否则将无法编译。
I have a constexpr function that looks something like this:
constexpr int foo(int bar)
{
static_assert(bar>arbitrary_number, "Use a lower number please");
return something_const;
}
However, compiling this with GCC 4.6.3 keeps telling me
error: 'bar' cannot appear in a constant-expression
I tried something like
constexpr int foo(constexpr const int bar)
{
static_assert(bar>arbitrary_number, "Use a lower number please");
return something_const;
}
but constexpr can't be used for function arguments.
Is there some simple way to tell the compiler that bar is always a compile time constant?
解决方案 If bar
is always compile-time constant, then you should write your function as:
template<int bar>
constexpr int foo()
{
static_assert(bar>arbitrary_number, "Use a lower number please");
return something_const;
}
Because if you don't do so, and instead write what you've already written, then in that case, the function can be called with non-const argument as well; it is just that when you pass non-const argument, then the function will loss it's constexpr-ness.
Note that in the above code arbitrary_number
should be constant expression as well, or else it will not compile.
这篇关于如何告诉static_assert constexpr函数参数是const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!