【发布时间】:2011-05-14 17:25:06
【问题描述】:
我正在尝试将访问者模式添加到我的代码中,并希望使其尽可能通用。更具体地说,我不想将回调函数硬编码到我的accept 函数中。所以,作为accept函数的参数,我给出了一个boost::function对象,然后被访问对象调用。
但是,我的问题是我无法绑定到重载函数(因为 boost::bind 不知道要绑定到哪个确切函数)并且我无法将重载函数强制转换为正确的函数,因为我不知道访问类的确切类型(这很重要)。
有什么方法可以创造我想要的东西吗?我搜索了 SO,但只发现有关如何解决绑定问题的问题(通过强制转换,这是我无法做到的)。
以下是一些无法编译的代码,但显示了我想要归档的内容:
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/function.hpp>
struct A
{
virtual void acceptVisitor (boost::function<void (A const &)> callbackFnc)
{
callbackFnc(*this);
}
};
struct B : virtual public A {};
std::string printMe (A const & a) { return "A"; }
std::string printMe(B const & a) { return "B"; }
int main()
{
std::vector<std::string> stringVector;
boost::function<void (A const &)> bindedFnc = boost::bind(&std::vector<std::string>::push_back,
&stringVector, boost::bind(&printMe, _1));
A A1;
B A2;
A1.acceptVisitor(bindedFnc);
A2.acceptVisitor(bindedFnc);
}
[编辑] 修正了示例代码,因为以前的版本(如 ildjarn 所说)实际上并未调用 accept 函数。
【问题讨论】:
-
请注意,您也不能获取
push_back的地址,因为它可能被重载(在 C++0x 中,它保证被重载)并且您不能使用强制转换,因为未指定标准库成员函数的类型(实现可以随意向其成员函数添加额外的重载和/或可选参数)。 -
"下面是一些无法编译的代码,但显示了我想要归档的内容" 不,它没有;
acceptVisitor在哪里发挥作用?实际访问在哪里?尝试描述你想要什么,因为你还没有有效地展示它。 -
@ildjarn 好点,固定示例代码。
标签: c++ boost visitor-pattern