10

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.

barej
  • 1,330
  • 3
  • 25
  • 56

3 Answers3

22

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 { .. }
    
David G
  • 94,763
  • 41
  • 167
  • 253
1

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

Barry
  • 286,269
  • 29
  • 621
  • 977
Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64
0

passing const CMyclass as this argument of void CMyclass::my_method(const state_type&, double) discards qualifiers

The error message says all. void CMyclass::my_method(const state_type&, double) expects a normal instance but not a const one. Change the method definition to

void CMyclass::my_method(const state_type&, double) const;

to resolve the error, or change the [=] lambda initialiser to whatever you need there (e.g. [&], but make sure it is not const.

msrd0
  • 7,816
  • 9
  • 47
  • 82