#include <iostream>
#include <functional>
class foo
{
public:
foo()
{
val = 42;
};
void bar(std::function<int(foo*)> f)
{
this->_bar = std::bind(f, this);
}
std::function<int()> _bar;
int val;
};
int main(void)
{
foo *foobar;
foobar->bar([](foo *self)->int{return self->val;});
std::cout << foobar->_bar();
}
最佳答案
这是段错误,因为 foobar 没有指向任何东西,你应该使用 foo foobar;。
编辑:
一个简短的评论。
class foo
{
public:
foo()
{
val = 42; // Use initialization list.
};
void bar(std::function<int(foo*)> f) // Use reference (foo&) instead of pointer (foo*).
{
this->_bar = std::bind(f, this); // Move "f" into bind and use "std::ref()" so you can pass "*this" by reference without copying.
}
// Hide local member variables
std::function<int()> _bar; // Never use _ as a prefix, only the compiler is allowed to use _ prefix.
int val;
};
int main(void)
{
foo *foobar; // Use value semantics, i.e. "foo foobar".
foobar->bar([](foo *self)->int{return self->val;});
std::cout << foobar->_bar();
}
例如
class foo
{
public:
foo()
: val_(42)
{
};
void set_bar(std::function<int(foo&)> f)
{
bar_ = std::bind(std::move(f), std::ref(*this));
}
int invoke_bar() const
{
return bar_;
}
int get_val() const
{
return val_;
}
private:
std::function<int()> bar_;
int val_;
};
int main(void)
{
foo foobar;
foobar.set_bar([](foo& self) -> int
{
return self.get_val();
});
std::cout << foobar.invoke_bar();
}