传递成员函数以创建自由函数提升指针(Pass a member function to create a free function boost pointer)

编程入门 行业动态 更新时间:2024-10-26 12:22:22
传递成员函数以创建自由函数提升指针(Pass a member function to create a free function boost pointer)

我试着让这段代码运行。 我几乎在那里,但我遇到了这条线:

_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.)

更多推荐

本文发布于:2023-08-04 07:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1413172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   指针   成员   自由   Pass

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!