c++ - 使用 constexpr 和 lambda 时出现编译器错误

标签 c++ gcc c++11 lambda constexpr

我在将 constexpr 函数与 lambda 一起使用时遇到了问题。 以下代码是重现错误的最小版本:

#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 中的错误还是我做错了什么?

最佳答案

Gcc 4.6 是 the first version to support constexpr ,并且在发布此类功能时出现小错误的情况并不少见。你可以验证 from this Live Example on Coliru gcc 4.8.1 和 Clang 3.4 SVN 正确解析您的代码。您可能应该相应地升级您的编译器。

关于c++ - 使用 constexpr 和 lambda 时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18232708/

相关文章:

成员方法中的 C++11 Lambda 函数继承作用域

c++ - 在自定义类中包装 std::packaged_task

c++ - const_iterator 和 const 指针

c++ - 4.5 规则 : No move assignment operator?

c++ - 减少程序的内存使用

c++ - Cygwin C++ 编译器

c++ - 多次使用 header 不好吗?

android - 硬浮点调用 GCC 中的某些函数

gcc - gcc "-Xlinker"和 "-Wl,"选项之间的区别?

c++ - C++11 中带有可变参数模板的 bindParameter 函数