如何告诉static_assert constexpr函数参数是const? [英] How to tell static_assert that constexpr function arguments are const?

查看:157
本文介绍了如何告诉static_assert constexpr函数参数是const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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总是一个编译时常数?


如果 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?

解决方案

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆