针对不同类型的矢量指针的演员

时间:2013-07-21 19:42:11

标签: c++ pointers vector casting

我有一个需要指向uint16_t类型向量的指针的函数。此函数用数据填充向量。我还有一个对象应该保存数据,但是以uint8_t类型的向量的形式。我的代码如下:

void fill1(vector<uint16_t> *data);
void fill2(vector<uint64_t> *data);

class Object
{
    uint32_t data_depth;
    vector<uint8_t> data;
}

Object object1;
object1.data_depth = 16;
fill1((vector<uint16_t>*) &object1.data);

Object object2;
object2.data_depth = 64;
fill2(vector<uint64_t>*) &object2.data);

// somewhere later in the code
if (object1.data_depth == 16)
   vector<uin16_t> * v = (vector<uint16_t>)(&objec1.data);

是不同类型矢量指针转换的保存方式吗?

2 个答案:

答案 0 :(得分:3)

你可能会这样做:

template <typename T>
void fill(vector<unsigned char>& data)
{
    assert(data.size() % sizeof(T) == 0);

    T* pReinterpreted = reinterpret_cast<T*>(&data[0]);
    size_t count = data.size() / sizeof(T);

    // do some stuff with your array of reinterpreted values
}

class Object
{
    uint32_t data_depth;
    vector<unsigned char> data;
}

Object object;
fill<uint16_t>(object.data);

当然,这是不安全的代码所以我不会这样做,除非你确切知道这里有什么权衡。

答案 1 :(得分:1)

这不安全。在基础级别,向量不是类型的数组,而是包含一些数据的对象,包括指向该类型数组的指针。你做的那个演员会导致对附加数据的误解。实际上,你甚至不能保证vector的实现不依赖于类型(我怀疑这是在任何地方都做到的 - 除了vector<bool>之外以不同的方式实现 - 但只要所有单独的实现都符合标准,它肯定是允许的。

您可以使用boost::variant允许不同基本类型的向量存储在Object::data中。

以下是您的代码的外观:

#include <boost/variant.hpp>

class Object
{
  boost::variant<std::vector<uint16_t>, std::vector<uint64_t> > data;
};

struct fill_visitor: boost::static_visitor<>
{
  template<typename T>
   void operator()(std::vector<T>& v)
  {
    fill(&v);
  }
};

// ...

boost::apply_visitor(fill_visitor(), object1.data);
相关问题