如何在 C++ 中实现基本的 Variant(以及 Variant 上的访问者)模板?
我尝试阅读:
http://www.boost.org/doc/libs/1_41_0/boost/variant.hpp
http://www.codeproject.com/KB/cpp/TTLTyplist.aspx
and chapter 3 of "Modern C++ Design"
但仍然不明白变体是如何实现的。任何人都可以粘贴一个简短的示例来说明如何定义类似的内容:
class Foo {
void process(Type1) { ... };
void process(Type2) { ... };
};
Variant<Type1, Type2> v;
v.somethingToSetupType1 ...;
somethingToTrigger process(Type1);
v.somethingToSetupType2 ...;
somethingToTrigger process(Type2);
谢谢!
I have tried reading:
http://www.boost.org/doc/libs/1_41_0/boost/variant.hpp
http://www.codeproject.com/KB/cpp/TTLTyplist.aspx
and chapter 3 of "Modern C++ Design"
but still don't understand how variants are implemented. Can anyone paste a short example of how to define something like:
class Foo {
void process(Type1) { ... };
void process(Type2) { ... };
};
Variant<Type1, Type2> v;
v.somethingToSetupType1 ...;
somethingToTrigger process(Type1);
v.somethingToSetupType2 ...;
somethingToTrigger process(Type2);
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我必须定义一个变体对象,我可能会从以下开始:
然后使用 MPL 向量 使该方法不仅适用于两种不同类型。
最后,你可以写这样的东西:
注意:这段代码不可能编译,但这描述了我使用的想法。
If i had to define a variant object, i'd probably start with the following :
then use MPL vectors to make the approach work for more than just two different types.
In the end, you could write something like this :
NB : there is no chance this code compiles, but this describes the ideas i'd use.
我认为您是在问如何使用变体,而不是如何实现它们。您可能需要查看有关变体的 Boost 文档;这比查看头文件更有帮助。
那么你的例子可能看起来像这样:
I think you are asking how to use variants, not how to implement them. You may want to look at the boost documentation on variants; this will be much more helpful than looking at the header file.
Then your example might look something like this: