【发布时间】:2014-06-27 11:18:04
【问题描述】:
考虑以下代码:
static constexpr int make_const(const int i){
return i;
}
void t1(const int i)
{
constexpr int ii = make_const(i); // error occurs here (i is not a constant expression)
std::cout<<ii;
}
int main()
{
t1(12);
}
为什么我在调用 make_const 时出错?
更新
但这一个有效:
constexpr int t1(const int i)
{
return make_const(i);
}
但是,这不是:
template<int i>
constexpr bool do_something(){
return i;
}
constexpr int t1(const int i)
{
return do_something<make_const(i)>(); // error occurs here (i is not a constant expression)
}
【问题讨论】:
-
好吧,因为在一般情况下,
i在void t1(const int)中不是constexpr。 -
那我怎样才能使它成为 constexpr 呢?
-
将其作为模板参数是您唯一的选择
-
没有直接的方法可以做你想做的事。此功能/限制可能是有关 constexpr 的最常见问题。