【发布时间】:2016-03-01 15:35:05
【问题描述】:
考虑以下代码:
struct A {
constexpr operator int() { return 42; }
};
template <int>
void foo() {}
void bar(A a) {
foo<a>();
}
int main() {
foo<A{}>();
const int i = 42;
foo<i>(); // (1)
A a{};
static_assert(i == a, "");
bar(a);
foo<a>(); // error here
}
带有 c++14 的 Clang 3.7 接受这一点,而带有 c++14 的 gcc 5.2.0 不接受,产生以下消息:
/tmp/gcc-explorer-compiler1151027-68-1f801jf/example.cpp: In function 'int main()': 26 : error: the value of 'a' is not usable in a constant expression foo<a>(); ^ 23 : note: 'a' was not declared 'constexpr' A a{}; ^ Compilation failed
按照 gcc 的建议将 a 更改为 constexpr 可修复 gcc 编译错误,但没有 constexpr,哪个编译器是正确的?
对我来说,a 似乎应该“可用于常量表达式”,正如static_assert 所证明的那样。而且i可以用同样的方式(标记(1)),bar()编译,也让我觉得gcc错了。
UPD:报告了一个针对 gcc 的错误:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68588
【问题讨论】:
-
将
const更改为constexpr工作Demo。 -
@Jarod42,是的,看看我的编辑。
标签: c++ templates gcc clang c++14