我在将 constexpr 函数与 lambdas 一起使用时遇到了问题。以下代码是重现错误的最小版本:
#include <iostream>
constexpr unsigned bar(unsigned q) {
return q;
}
template<unsigned N>
unsigned foo() {
return N;
}
template<typename F>
void print(F f) {
std::cout << f() << std::endl;
}
template<unsigned Q>
int stuff() {
constexpr unsigned n = bar(Q);
print([]() { return foo<n>(); });
}
int main() {
stuff<13>();
}
编译时gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
出现以下编译器错误:
constexpr_template.cpp: In lambda function:
constexpr_template.cpp:24:9: instantiated from ‘stuff() [with unsigned int Q = 13u]::<lambda()>’
constexpr_template.cpp:24:2: instantiated from ‘int stuff() [with unsigned int Q = 13u]’
constexpr_template.cpp:29:12: instantiated from here
constexpr_template.cpp:24:32: error: no matching function for call to ‘foo()’
constexpr_template.cpp:24:32: note: candidate is:
constexpr_template.cpp:9:10: note: template<unsigned int N> unsigned int foo()
现在奇怪的是,如果constexpr unsigned n = bar(Q);
改成constexpr unsigned n = Q;
它就可以了。同样有效的是print([]() { return foo<bar(Q)>(); });
......
这是 GCC 中的错误还是我做错了什么?