Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何告诉static_断言constexpr函数参数是const?_C++_C++11_Constexpr - Fatal编程技术网

C++ 如何告诉static_断言constexpr函数参数是const?

C++ 如何告诉static_断言constexpr函数参数是const?,c++,c++11,constexpr,C++,C++11,Constexpr,我有一个constexpr函数,看起来像这样: constexpr int foo(int bar) { static_assert(bar>arbitrary_number, "Use a lower number please"); return something_const; } 然而,用GCC4.6.3编译它一直告诉我 错误:“条”不能出现在常量表达式中 我试过类似的东西 constexpr int foo(constexpr const int bar) {

我有一个constexpr函数,看起来像这样:

constexpr int foo(int bar)
{
   static_assert(bar>arbitrary_number, "Use a lower number please");

   return something_const;
}
然而,用GCC4.6.3编译它一直告诉我

错误:“条”不能出现在常量表达式中

我试过类似的东西

constexpr int foo(constexpr const int bar)
{
   static_assert(bar>arbitrary_number, "Use a lower number please");

   return something_const;
}
但是constexpr不能用于函数参数

有没有简单的方法告诉编译器bar始终是编译时常量

有没有简单的方法告诉编译器bar始终是编译时常量

如果
bar
始终是编译时常量,则应将函数编写为:

template<int bar>
constexpr int foo()
{
   static_assert(bar>arbitrary_number, "Use a lower number please");
   return something_const;
}
模板
constexpr int foo()
{
静态断言(条形图>任意数字,“请使用较低的数字”);
归还某物;
}
因为如果你不这样做,而是写你已经写的,那么在这种情况下,函数也可以用非常量参数调用;只是当您传递非常量参数时,函数将失去其常量


请注意,在上述代码中,任意数也应为常量表达式,否则它将无法编译。

foo
可按以下方式使用:

int i;
std::cin >> i;
foo("foo", i);
正如您所看到的,
i
并不是上述的常量表达式,但它仍然可以与
constepr
函数一起使用
constexpr
函数(和函数模板)是一个奇怪的野兽,它保证了例如
foo(p,i)
是一个常量表达式,如果
p
i
也是,但仍然可以像常规函数一样使用


如果函数的参数真的总是常量表达式,那么它们应该是模板参数,而不是函数参数。

constexpr
函数可以在编译时进行计算,通常不受标准的强制(您可以通过在常量表达式中使用函数,如初始化
constexpr
变量,强制在编译时对函数求值)

另外,
constexpr
函数的参数实际上不是常数,它们可能会随着每次调用而变化(即使在编译时进行计算)


一种解决方法是使用非类型模板传递
bar
,前提是它始终是编译时常量(看起来是这样的).

Oops,完全忘记了对该部分进行编码。感谢@HenrikA constexpr函数可以用非常量参数调用,它只会失去其constexpr特性。什么类型的语法是
template
?像
template…