访问者模式是在 C++ 中完成方法参数类型识别(有效地单次调度参数,而不是成员的类)的最快方法吗?我可能知道我想对未知子类型的元素调用的确切方法,因此总是不希望像V::visit(A *)
in那样进行额外的虚拟方法调用A::accept(V &v) { v.visit(this); }
。
// Is the Visitor pattern recommended here? (E inherits D inherits B.)
class Foo {
public:
virtual void visit(B *) { result = 3; }
virtual void visit(D *) { result = 4; }
virtual void visit(E *) { result = 5; }
private:
int result;
}; // class Foo
// Need to add generic interface to B and its children ...
class B {
public:
virtual void accept(class Foo &f) { f.visit(this); }
}; // class B
我想要以下功能等效的东西,但成本为 O(1),这是 AFAIK 无法使用 dynamic_cast<> 或 typeid() 梯子,因为std::type_info
不能是 constexpr/switchable。
// O(n) search cost might get nasty with bigger hierarchies.
int foo(B *b) {
if (typeid(b) == typeid(B *)) { return 1; }
if (typeid(b) == typeid(D *)) { return 2; }
if (typeid(b) == typeid(E *)) { return 3; }
return -1;
}
我在这里有什么选择?感谢您的建议!
编辑:更改了示例代码以通过字段提供结果,这样不同的方法类型就不需要多个签名。谢谢,莫里斯!
最终决定:除了不喜欢访问者模式的强制双重调度成本之外,我还想避免接口膨胀的重载foo()
,但我认为没有已知的干净模式可以做到这一点。我最终只是做了直接的静态重载,然后就收工了。无论如何,我想将重载封装在一个函数中可能充其量是一个值得商榷的目标。谢谢,莫里斯的回应。