简体   繁体   English

C++ 模板,用于通过常量引用和原始指针传递向量

[英]C++ template for both passing a vector by constant reference and raw pointer

(Trivial template specialization isn't a silver bullet in this case!) (在这种情况下,简单的模板专业化并不是灵丹妙药!)

I am working on some image processing code and am interfacing with some Cython.我正在处理一些图像处理代码,并正在与一些 Cython 进行交互。 To interact with Cython I need to pass a raw pointer to a function to avoid copy overhead.要与 Cython 交互,我需要将原始指针传递给 function 以避免复制开销。 I realized that it would be nice to work with boolean images to save memory in some cases, so ideally I could change the declaration from:我意识到在某些情况下使用 boolean 图像来保存 memory 会很好,所以理想情况下我可以更改声明:

template <typename T>
uint32_t* connected_components(
    T* in_labels, ...
)

To this:对此:

template <typename T>
uint32_t* connected_components(
    const std::vector<T> &in_labels, ...
)

However, to support the bit packed case, I can't just cast the vector's container to a pointer in a specialization, I need to preserve the vector class semantics.但是,为了支持位压缩情况,我不能只将向量的容器转换为专门化的指针,我需要保留向量 class 语义。

Is there a way to write this template such that it will declare in_labels as both a pointer and a vector?有没有办法编写这个模板,以便它将in_labels声明为指针和向量? I can just copy the code, but I'd rather not as it is a rather complex implementation of a fast algorithm.我可以只复制代码,但我不想这样做,因为它是快速算法的一个相当复杂的实现。

Edit: I suppose a giant macro would work... but it's ugly.编辑:我想一个巨大的宏会起作用......但它很难看。

I think I figured out a simpler solution.我想我想出了一个更简单的解决方案。 I'll just make the vector specialization contain the algorithmic code and cast the raw pointer to a vector in its own specialization.我只是让向量特化包含算法代码,并将原始指针转换为它自己的特化中的向量。 I'll then let Cython interact with the pointer specialization while other uses can default to the vector specialization.然后,我将让 Cython 与指针特化交互,而其他用途可以默认为向量特化。

template <typename T>
uint32_t* connected_components3d_26(
    const std::vector<T> &in_labels, 
    const int64_t sx, const int64_t sy, const int64_t sz,
    int64_t max_labels, uint32_t *out_labels = NULL
  ) {

    // algorithm goes here
}


template <typename T>
uint32_t* connected_components3d_26(
    T* in_labels, 
    const int64_t sx, const int64_t sy, const int64_t sz,
    int64_t max_labels, uint32_t *out_labels = NULL
  ) {

  std::vector<T> vec_in_labels;
  vec_in_labels.assign(in_labels, in_labels + sx * sy * sz);

  return connected_components3d_26(
    vec_in_labels, 
    sx, sy, sz,
    max_labels, out_labels
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM