非循环访客模式.将接受函数移动到一个位置
Acyclic visitor pattern. Moving the accept function to just one place
下面我从Object
中取出了accept (const ChooseVisitor&);
函数并将其放在Menu<T>::Option
中,这样只需要在那里调用它,而不是许多具有accept
函数的类。 唯一的问题是T
可能是指针或引用,或者其他什么,我需要变成没有指针或引用或常量等的常规类型......获取T::Visitor*
进行编译。
#include <iostream>
#include <type_traits>
struct ChooseVisitor {
virtual ~ChooseVisitor() = default;
};
struct Object {
struct Visitor {
virtual void visit (Object*) const = 0;
};
// void accept (const ChooseVisitor&); // I've decided to move this into Menu instead (to avoid the repetitions in other classes).
};
struct PurchaseObjectVisitor : public ChooseVisitor, public Object::Visitor {
virtual void visit (Object* object) const {
std::cout << object << " purchased.n";
}
};
template <typename T>
struct Menu {
struct Option {
T item;
template <typename> void accept (const ChooseVisitor&);
};
Option* option; // Assume Menu<T> with only one option for simplicity here.
template <typename> void choose() const;
void insert (const T& t) {option = new Option{t};}
};
template <typename T>
template <typename Visitor>
void Menu<T>::Option::accept (const ChooseVisitor& visitor) {
// using Type = typename std::remove_pointer<T>::type; // How to cover all possible cases?
const typename Type::Visitor* v = dynamic_cast<const typename Type::Visitor*> (&visitor);
if (v) v->visit(item);
}
template <typename T>
template <typename Visitor>
void Menu<T>::choose() const {
const Visitor visitor;
option->template accept<Visitor>(visitor); // template disambiguator needed.
}
int main() {
Menu<Object*> menu;
menu.insert (new Object);
menu.choose<PurchaseObjectVisitor>();
}
我从
template <typename T>
struct GetVisitor {
using type = std::is_pointer<T>::value ? typename std::remove_pointer<T>::type::Visitor : typename T::Visitor;
};
但它现在不起作用,而且它需要处理所有可能的类型。 最优雅的方法是什么? 有没有一个简单的功能已经这样做了?
你错过了::type
.应该是std::remove_pointer<T>::type
更新:要获得纯类型,您可以嵌套std::remove_
模板 - std::remove_cv<typename std::remove_pointer<typename std:: remove_reference<T>::type>::type>::type
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 将一个向量插入另一个向量的某个位置
- 将所有 URL 组织在类中的一个位置
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 如何在另一个字符串的x位置插入一个字符串?
- C++强制变量到一个固定的内存位置
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- 在多维向量中的特定位置添加一个值
- C++将包含的库 (ref DLL) 从根目录更改为另一个位置
- 查找 2D 向量的位置,该向量是类C++的一个元素
- 创建一个函数以在给定位置将元素插入到列表中
- C++11 中的随机数:有没有一种简单的方法可以将生成器种子放在代码的一个位置,然后在不同的函数中使用它?
- 快速从文件中读取下一个字符串,而无需移动文件的位置
- 给定一个用三角形镶嵌的补丁,如何修改其新的顶点位置
- 如何正确删除一行控件并在该位置动态创建一个新控件
- 如何在点击的QPushButton的位置画一个形状
- 如何编写一个 void 函数,该函数将在数组中搜索值,并通过引用将该值的位置传递回 main 函数
- 将过滤器中的所有.cpp和.h移动到另一个项目并更正其文件夹位置
- 如何在 MFC 中围绕当前光标的位置绘制一个矩形
- 访问违反读数位置时,当另一个垫子中的push_back垫子