I have a little example here below that has two functions (getFoo1...2) that returns a std::function.
- In both cases the getters are const.
- getFoo1 generates the return type by using a lambda with a this capture.
- getFoo2 generates the return type by using std::bind.
- In both cases the real function is non-const.
- The lambda case compiles fine (therefore constness lost...).
- The binder complains about constness of this (as expected, as the member function pointer is non const and requires a non const T to bind on).
I'm concerned with regards to the lambda behaviour (I EXPECTED IT TO NOT COMPILE, AS WITH getFoo2). Any insights would be welcome.
Note: Compiler used GCC 4.8.*.
#include <iostream>
#include <functional>
struct X
{
void foo(){ std::cout << " non const !!!! foo called" << std::endl;}
std::function<void()> getFoo1() const
{
//Compiles, even though "non const" this required...
return [this]{foo();};
}
std::function<void()> getFoo2() const
{
//Fails to compiler due to non const this required
return std::bind(&X::foo, this);
}
};
int main()
{
X().getFoo1()();
X().getFoo2()();
return 0;
}
Kind regards,
Werner
Aucun commentaire:
Enregistrer un commentaire