问题描述
我一直在尝试通过使用 C++ 模板来实现访问者模式来减少代码中样板的数量.到目前为止,我想出了这个:
I've been trying to reduce the amount of boilerplate in my code, by using C++ Templates to implement the visitor pattern. So far I've come up with this:
Visible 的每个子类如下所示:
And each subclass of Visitable looks like this:
最后访问者看起来像这样:
And finally the Visitor looks like this:
到目前为止一切顺利……现在问题来了:
So far so good... now here's the problem:
我需要以某种方式强制转换为 Visitable 以便我可以调用 accept(),但显然我不知道 T 是什么.或者,我无法向 Visitable 模板添加虚拟 accept(),因为我不知道它应该采用什么参数.
I need to somehow cast to Visitable so that I can call accept(), but obviously I don't know what T is. Alternatively I can't add a virtual accept() to the Visitable template, because I don't know what argument it should take.
任何 C++ 模板大师都知道如何使这个工作?
Any C++ Templating guru's out there know how to make this work?
推荐答案
这可以在 C++11 中使用可变参数模板来完成.继续皮特的回答:
This can be done in C++11 using variadic templates. Continuing from Pete's answer:
Visitable
的子类:
一个 Visitor
子类:
不清楚你的 Scene
容器的 value_type
是什么,但你需要获得一个引用或指向 Visitable
调用accept
:
It's not clear what the value_type
of your Scene
container is but you need to obtain a reference or pointer to Visitable<Mesh, Text>
on which to call accept
:
这篇关于使用 C++ 模板实现访问者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!