考虑一下片段:
# include <iostream>
# include <boost/scoped_ptr.hpp>
# include <boost/shared_ptr.hpp>
# include <boost/function.hpp>
# include <boost/array.hpp>
# include <boost/asio.hpp>
# include <boost/thread.hpp>
# include <boost/thread/locks.hpp>
# include <boost/bind.hpp>
# include <boost/noncopyable.hpp>
# include <boost/variant.hpp>
class DataLink {};
class Metadata {};
class Image {};
typedef boost::function<void( DataLink const&, Metadata const& , Image const& )> Handler ;
typedef boost::function<void( Metadata const& , Image const& )> Handler2 ;
typedef boost::function<void( Image const& )> Handler3 ;
typedef boost::variant<DataLink, Metadata, Image> Variant;
enum callbackHandler { link_enum, meta_enum, image_enum };
class Worker {
Handler callBack ;
//Handler2 callBack2 ;
//Handler3 callBack3 ;
DataLink dlink;
Metadata meta ;
Image img ;
callbackHandler handlerEnum ;
public :
Worker ( const Handler& handler )
: callBack ( handler )
{}
//Worker ( const Handler2& handler )
//: callBack2 ( handler )
// {}
//Worker ( const Handler3& handler )
//: callBack3 ( handler )
// {}
void Image ( ) {
// update the img object
// invoke call back
handlerEnum = image_enum ;
//const std::type_info& xxx = callBack.target_type();
//std::cout << xxx.raw_name() << std::endl;
callBack ( dlink, meta, img ) ;
}
void Metadata ( ) {
// update the meta object
// invoke call back
handlerEnum = meta_enum ;
callBack ( dlink, meta, img ) ;
}
void Dlink ( ) {
// update the link object
// invoke call back
handlerEnum = link_enum ;
callBack ( dlink, meta, img ) ;
}
callbackHandler getHandlerType() { return handlerEnum ; }
};
class Foo {
Worker *ptrWorker ;
public :
Foo ()
: ptrWorker( 0 )
{}
void callback ( DataLink const& d, Metadata const& m , Image const& i ) {
callbackHandler tt = ptrWorker->getHandlerType();
if ( tt == image_enum ) {
std::cout << "Image object " << std::endl;
}
if ( tt == meta_enum ) {
std::cout << "Meta object " << std::endl;
}
if ( tt == link_enum ) {
std::cout << "Link object " << std::endl;
}
}
bool start () {
ptrWorker = new ( std::nothrow ) Worker ( boost::bind ( &Foo::callback, this, _1, _2, _3 ) );
if ( !ptrWorker ) {
return - 1 ;
}
}
void testWorker() {
ptrWorker->Image() ;
ptrWorker->Metadata() ;
ptrWorker->Dlink() ;
}
};
int main() {
Foo f;
f.start() ;
f.testWorker() ;
std::cin.get() ;
}
注释掉的构造函数允许我添加对 Handler2 和 Handler3 的支持,但是有没有办法确定传递给 Worker 类的构造函数的处理程序?目前成员函数 Metadata、Image 和 Dlink 使用 'callBack' 对象。如果用户处理程序传入另一个处理程序,我需要区分 - 比如说 Handler2
我需要使用枚举来实现,实际上是我自己的类型系统(按照歧视性联合 - 也就是变体),这一事实也是一个明确的迹象,表明设计需要重新思考这种情况下,我愿意重新设计。必须在类中定义 N-1 个虚拟处理程序(即,在任何时候都只使用一个处理程序,而其他处理程序什么都不做)会让人感到困惑和低内聚的对象模型,但谁知道呢。