【发布时间】:2015-03-05 01:49:49
【问题描述】:
我正在 C++14 中试验 constexpr 函数。以下代码计算阶乘按预期工作:
template <typename T>
constexpr auto fact(T a) {
if(a==1)
return 1;
return a*fact(a-1);
}
int main(void) {
static_assert(fact(3)==6, "fact doesn't work");
}
当用clang编译如下:
> clang++ --version
clang version 3.5.0 (tags/RELEASE_350/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
> clang++ -std=c++14 constexpr.cpp
但是,当我将 fact 定义更改为使用三元 ? 运算符时:
template <typename T>
constexpr auto fact(T a) {
return a==1 ? 1 : a*fact(a-1);
}
我收到以下编译器错误:
> clang++ -std=c++14 constexpr.cpp
constexpr.cpp:12:31: fatal error: recursive template instantiation exceeded maximum depth of
256
return a==T(1) ? T(1) : a*fact(a-1);
... snip ...
constexpr.cpp:16:19: note: in instantiation of function template specialization 'fact<int>'
requested here
static_assert(fact(3)==6, "fact doesn't work");
如果我明确声明返回类型 T(而不是使用 auto 推断返回类型),问题就解决了
template <typename T>
constexpr T fact(T a) {
return a==1 ? 1 : a*fact(a-1);
}
如果我删除模板参数,模式会重复(三元版本失败,if 版本有效)
// this works just fine
constexpr auto fact(int a) {
if(a==1)
return 1;
return a*fact(a-1);
}
而这失败了
constexpr auto fact(int a) {
return a==1 ? 1 : a*fact(a-1);
}
出现以下错误
> clang++ -std=c++14 constexpr.cpp
constexpr.cpp:16:25: error: function 'fact' with deduced return type cannot be used before it
is defined
return a==1 ? 1 : a*fact(a-1);
^
constexpr.cpp:15:16: note: 'fact' declared here
constexpr auto fact(int a) {
^
constexpr.cpp:20:26: error: invalid operands to binary expression ('void' and 'int')
static_assert(fact(3)==6, "fact doesn't work");
~~~~~~~^ ~
2 errors generated.
这是怎么回事?
【问题讨论】:
标签: c++ ternary-operator c++14 constexpr