如何boost :: variant和boost ::任何工作? [英] How do boost::variant and boost::any work?

查看:227
本文介绍了如何boost :: variant和boost ::任何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

``````````````````````````````在我正在开发的项目中,我目前使用一个标记的联合。我想使用其他的东西,因为C ++的联合不允许你使用对象的构造函数,析构函数或重载的赋值运算符。

How do variant and any from the boost library work internally? In a project I am working on, I currently use a tagged union. I want to use something else, because unions in C++ don't let you use objects with constructors, destructors or overloaded assignment operators.

我查询任何和变体的大小,并与他们做了一些实验。在我的平台,variant取其最长的类型加上8字节的大小:我认为我只是8字节的类型信息,其余的是存储的值。另一方面,任何只需要8个字节。因为我在一个64位的平台上,我想任何只是持有一个指针。

I queried the size of any and variant, and did some experiments with them. In my platform, variant takes the size of its longest possible type plus 8 bytes: I think it my just be 8 bytes o type information and the rest being the stored value. On the other hand, any just takes 8 bytes. Since i'm on a 64-bit platform, I guess any just holds a pointer.

任何知道它的类型是什么? Variant如何通过模板实现它做什么?

How does Any know what type it holds? How does Variant achieve what it does through templates? I would like to know more about these classes before using them.

推荐答案

如果你阅读boost ::任何文档,他们提供了创意来源: http://www.two-sdg.demon.co.uk /curbralan/papers/ValuedConversions.pdf

If you read the boost::any documentation they provide the source for the idea: http://www.two-sdg.demon.co.uk/curbralan/papers/ValuedConversions.pdf

这是基本的信息隐藏,一个重要的C ++技能。

It's basic information hiding, an essential C++ skill to have. Learn it!

由于这里最高的投票答案是完全不正确的,我有疑问,人们会实际去看看源代码来验证这个事实,这里是一个基本的实现一个任何类似的接口,它将包装任何类型的f()函数,并允许它被调用:

Since the highest voted answer here is totally incorrect, and I have my doubts that people will actually go look at the source to verify that fact, here's a basic implementation of an any like interface that will wrap any type with an f() function and allow it to be called:

struct f_any
{
   f_any() : ptr() {}
   ~f_any() { delete ptr; }
   bool valid() const { return ptr != 0; }
   void f() { assert(ptr); ptr->f(); }

   struct placeholder
   {
     virtual ~placeholder() {}
     virtual void f() const = 0;
   };

   template < typename T >
   struct impl : placeholder
   {
     impl(T const& t) : val(t) {}
     void f() const { val.f(); }
     T val;
    };
   // ptr can now point to the entire family of 
   // struct types generated from impl<T>
   placeholder * ptr;

   template < typename T >
   f_any(T const& t) : ptr(new impl<T>(t)) {}

  // assignment, etc...
};

boost :: any除了f()实际返回 typeinfo const& 并提供其他信息访问any_cast函数。

boost::any does the same basic thing except that f() actually returns typeinfo const& and provides other information access to the any_cast function to work.

这篇关于如何boost :: variant和boost ::任何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆