Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing ‘const CMyclass’ as ‘this’ argument of ... discards qualifiers [-fpermissive]

compiling the following code via

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

gives me the following error:

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);};
                                                                                                                                ^

I have searched other similar questions but I can't figure out what is wrong with this code.

#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);
         };
}

edit:

I would not put const after the method.

like image 770
barej Avatar asked Dec 20 '14 20:12

barej


2 Answers

Since you're taking by value my_class becomes const-qualified. You have three options to fix it:

  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 { .. }
    
like image 180
David G Avatar answered Oct 17 '22 15:10

David G


You have to mark your lambda mutable

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

full code below

#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);
        };
}

compiled by g++ -Wall -std=c++11, gcc v4.9.2

like image 45
Severin Pappadeux Avatar answered Oct 17 '22 15:10

Severin Pappadeux