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.
Since you're taking by value my_class
becomes const
-qualified. You have three options to fix it:
Add const
to your method:
void my_method(const state_type &x, const double t) const
Capture by reference:
[&](const state_type &x, const double t) { .. }
Or make the lambda mutable:
[=](const state_type &x,const double t) mutable { .. }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With