[英]How can I implement the visitor patter with return type in C++
我想為我的 class 之一實現訪問者模式,而不必依賴將實現訪問它們的接口的類型。
我的解決方案是這樣的:
class model::VisitableNode {
public:
template<class T>
virtual T accept(NodeVisitor<T>);
}
但是 C++ 說它不支持模板+虛擬方法
我的應用程序中的節點將只有一個實現,但如果我不使用模板返回類型,我的 model class 將取決於我用來為我的應用程序創建圖形的工具包。
如果訪問者需要返回值,將返回值存儲在訪問者本身中是正常的。 因此:
NodeVisitor<double> dv;
node->accept(dv);
double result = dv.result();
如果您不喜歡樣板,可以將其包裝在非虛擬成員中:
class model::VisitableNode {
public:
template<class T>
/* non-virtual */ T accept(NodeVisitor<T>& v) {
do_accept(v);
return v.result;
}
virtual void do_accept(NodeVisitorBase& v) = 0;
}
為什么不模板化 class 本身?
template<class T>
class model::VisitableNode<T> {
public:
virtual T accept(NodeVisitor<T>);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.