我试着让这段代码运行。 我几乎在那里,但我遇到了这条线:
_f = std::bind1st( std::mem_fun(f, x);首先请理解我不想更改任何代码,而是构造函数 。 为什么? 因为我想学习。 最后我想编写一个包装类Func ,它可以同时处理自由函数和成员函数。 那么我必须把它作为第一个参数放在std::mem_func() - std::mem_func() ? 我尝试了很多东西。 可能这是重复,但我不知道如何搜索这个问题。 我缺乏词汇量。 如果有人可以指向教程或其他东西,这将有助于我表达这个问题,我也会很感激。
以下是完整的示例代码:
#include <boost/function.hpp> #include <iostream> struct X { int foo(int i) { return i; }; }; class Func { public: Func(X *x, int (X::* f) (int)) { _f = std::bind1st( std::mem_fun(f, x); std::cout << _f(5); // Call x.foo(5) }; private: boost::function<int (int)> _f; }; int main() { X x; Func func(&x, &X::foo); return 0; }提前致谢。
I try to get this code running. I am almost there but I got stuck with the line:
_f = std::bind1st( std::mem_fun(f, x);First of all please understand that I don't want to change any code, but the constructor. Why? Because I want to learn. Eventually I want to write a wrapper class Func, that can handle free functions and member function at the same time, in this very manner. So what wuld I have to put as the first argument inside the std::mem_func()-call??? I tried numerous things. Probably this is a duplicate, but I don't know how to search for this problem. I lack the vocabulary. If someone can point to a tutorial or something, that would help me to express this problem, I would also appreciate it.
Here is the full sample code:
#include <boost/function.hpp> #include <iostream> struct X { int foo(int i) { return i; }; }; class Func { public: Func(X *x, int (X::* f) (int)) { _f = std::bind1st( std::mem_fun(f, x); std::cout << _f(5); // Call x.foo(5) }; private: boost::function<int (int)> _f; }; int main() { X x; Func func(&x, &X::foo); return 0; }Thanks in advance.
最满意答案
看来你刚忘了一个人:
_f = std::bind1st(std::mem_fun(f), x);虽然我会初始化
Func(X *x, int (X::* f) (int)) : _f(std::bind1st(std::mem_fun(f), x)) { std::cout << _f(5); // Call x.foo(5) };(在这种情况下无关紧要,但从长远来看,这种风格更安全。)
It seems you just forgot a paren:
_f = std::bind1st(std::mem_fun(f), x);Although I would initialize with
Func(X *x, int (X::* f) (int)) : _f(std::bind1st(std::mem_fun(f), x)) { std::cout << _f(5); // Call x.foo(5) };(It doesn't matter in this case, but this style is safer in the long run.)
更多推荐
发布评论