将“const CMyclass”作为“this”参数传递会丢弃限定符[-fpermissive]。

10

通过以下方式编译代码:

g++ -std=c++11 test.cpp

会出现以下错误:
test.cpp: In lambda function:
test.cpp:17:128: error: passing ‘const CMyclass’ as ‘this’ argument of ‘void CMyclass::my_method(const state_type&, double)’ discards qualifiers [-fpermissive]
  std::function<void(const state_type &,const double)> observer = [=](const state_type &x,const double t){my_class.my_method(x,t);};
                                                                                                                                ^

我搜索了其他类似的问题,但是我找不出这段代码的错误所在。

#include <vector>
#include <functional>

typedef std::vector<int> state_type;

class CMyclass
{
public:
    void my_method( const state_type &x , const double t )
    {
    }
};

int main()
{
    CMyclass my_class;
    std::function<void(const state_type &,const double)> observer =
         [=](const state_type &x,const double t)
         {
             my_class.my_method(x,t);
         };
}

编辑:

我不会在方法后面加上const

3个回答

22

由于您正在按值传递 my_class,因此它变为const限定。您有三个选项来解决这个问题:

  1. Add const to your method:

    void my_method(const state_type &x, const double t) const
    
  2. Capture by reference:

    [&](const state_type &x, const double t) { .. }
    
  3. Or make the lambda mutable:

    [=](const state_type &x,const double t) mutable { .. }
    

第二个选项正是我所需要的。 - barej

1
你必须将你的lambda标记为可变的。
observer = [=](const state_type &x,const double t) mutable {my_class.my_method(x,t);};

完整代码如下

#include <vector>
#include <functional>

typedef std::vector<int> state_type;

class CMyclass
{
public:
    void my_method( const state_type &x , const double t )
    {
    }
};

int main()
{
    CMyclass my_class;
    std::function<void(const state_type &,const double)> observer = 
        [=](const state_type &x,const double t) mutable {
            my_class.my_method(x,t);
        };
}

g++ -Wall -std=c++11 编译,gcc 版本为 v4.9.2。

0
传递const CMyclass作为void CMyclass::my_method(const state_type&, double)this参数会丢弃限定符。
错误信息已经说明了问题。 void CMyclass::my_method(const state_type&, double)期望一个普通实例而不是一个const实例。请更改方法定义为:
void CMyclass::my_method(const state_type&, double) const;

为了解决错误,或者将[=] lambda初始化器更改为您需要的内容(例如[&]),但请确保它不是const。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接