模板类成员方法内的自动 lambda:不命名类型

auto lambda inside template class member method: does not name a type

本文关键字:lambda 类型 成员方法      更新时间:2023-10-16

为什么我无法编译以下代码(使用 g++ 4.7.1)?

#include <set>
template<typename T>
class Problem
{
    public:
        void f();
        std::set<int> dummyvalue;
};
template<typename T>
void Problem<T>::f()
{
    auto mytestlambda = [this](){
        dummyvalue.clear();
    };
}
int main()
{
    return 0;
}

我收到以下错误:

main.cpp: In member function 'void Problem<T>::f()':
main.cpp:17:10: error: 'mytestlambda' does not name a type

我在检查无法调用"clear()"方法的问题时遇到了这个问题。

添加'-std=c++11'真的让我解决了我真正的问题:

main.cpp: In lambda function:
main.cpp:18:26: error: no matching function for call to 'std::set<int>::clear() const'
main.cpp:18:26: note: candidate is:
In file included from /usr/include/c++/4.7/set:61:0,
                 from main.cpp:1:
/usr/include/c++/4.7/bits/stl_set.h:580:7: note: void std::set<_Key, _Compare, _Alloc>::clear() [with _Key = int; _Compare = std::less<int>; _Alloc = std::allocator<int>] <near match>
/usr/include/c++/4.7/bits/stl_set.h:580:7: note:   no known conversion for implicit 'this' parameter from 'const std::set<int>*' to 'std::set<int>*'

为什么这里涉及"康斯特"?

这是

GCC 4.7中的一个错误。升级到 4.8 可以修复它。

显然,GCC 4.7错误地将this捕获为const

这是因为您在编译器中没有启用C++11。尝试使用 GCC --std=c++11标志。然后它应该编译正确。

尝试使用 -std=c++11 编译。可悲的是,当前的编译器仍然默认使用>10年的标准。