gpt4 book ai didi

c++ - boost::bind 到类成员函数

转载 作者:行者123 更新时间:2023-11-28 03:07:54 25 4
gpt4 key购买 nike

我正在尝试通过 boost::bind 将封装的成员函数传递给独立函数。以下是缩减后的样本。

// Foo.h
typedef const std::pair<double, double> (*DoubleGetter)(const std::string &);

class Foo : private boost::noncopyable {
public:
explicit Foo(const std::string &s, DoubleGetter dg);
};

// Bar.h
struct Bar {
const std::pair<double, double> getDoubles(const std::string &s);
};

// main.cpp
boost::shared_ptr<Bar> bar(new Bar());

std::string s = "test";
Foo foo(s, boost::bind(&Bar::getDoubles, *(bar.get()), _1));

但是我在文本中遇到了编译器错误:

/home/Loom/src/main.cpp:130: error: no matching function for call to 
‘Foo::Foo
( std::basic_string<char, std::char_traits<char>, std::allocator<char> >
, boost::_bi::bind_t
< const std::pair<double, double>
, boost::_mfi::mf1
< const std::pair<double, double>
, Bar
, const std::string&
>
, boost::_bi::list2
< boost::_bi::value<Bar>
, boost::arg<1>
>
>
)’

/home/Loom/src/Foo.h:32: note: candidates are:
Foo::Foo(const std::string&, const std::pair<double, double> (*)(const std::string&))

/home/Loom/src/Foo.h:26: note:
Foo::Foo(const Foo&)

代码有什么问题,如何避免这样的问题?

最佳答案

成员函数指针不包含上下文(与 lambda 或 boost::function 相对)。要使代码正常工作,您需要将 DoubleGetter 的类型定义替换为:

typedef boost::function<const std::pair<double, double>(const std::string&)> DoubleGetter;

此外,当您提供上下文 (Bar) 时,也无需取消引用智能指针(如果您打算这样做,您可以直接使用速记取消引用运算符):

// Pass the pointer directly to increment the reference count (thanks Aleksander)
Foo foo(s, boost::bind(&Bar::getDoubles, bar, _1));

我还注意到您定义了一个普通的函数指针。如果您想完全避免使用 boost::function,您可以使用以下方法(我排除了未更改的部分):

typedef const std::pair<double, double> (Bar::*DoubleGetter)(const std::string &);

class Foo : private boost::noncopyable {
public:
explicit Foo(const std::string &s, Bar& bar, DoubleGetter dg);
// Call dg by using: (bar.*dg)(s);
};

// Instantiate Foo with:
Foo foo(s, *bar, &Bar::getDoubles);

关于c++ - boost::bind 到类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19243784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com