设计需要划痕空间的算法

And*_*ndt 16 c++ algorithm boost boost-gil

C++标准库将数据结构与算法分开,例如std::sort:

template< class RandomAccessIterator >
void sort( RandomAccessIterator first, RandomAccessIterator last );
Run Code Online (Sandbox Code Playgroud)

当算法需要中间临时空间时,我想保持算法和数据结构的分离.

考虑到这一目标,我想实现一种图像算法,该算法需要输入和输出图像之间的中间划痕空间.可以在函数调用中分配必要的临时空间,但是由于具有相同大小的图像的这些调用的大小和频率,将严重降低性能.这使得将数据结构与算法分离变得更加困难.

实现此目的的一种可能方法如下:

// Algorithm function
template<typename InputImageView, typename OutputImageView, typename ScratchView>
void algorithm(
  InputImageView inputImageView, 
  OutputImageView outputImageView, 
  ScratchView scratchView
);

// Algorithm class with scratch space
template<typename DataStructure>
class Algorithm {
public:
  template<typename InputImageView,typename OutputImageView>
  void operator()(
  InputImageView inputImageView, 
  OutputImageView outputImageView
  ){
    m_scratch.resize(inputImageView.size());
    algorithm(inputImageView,outputImageView,makeView(m_scratch));
  }

private:
  DataStructure m_scratch;
}
Run Code Online (Sandbox Code Playgroud)

上面是一个有效的算法+划痕空间设计可以遵循,还是有更好的方法?

旁注:我正在使用boost :: gil

Jer*_*fin 3

我认为在这种情况下,我会让算法允许您传递(引用或指针)临时空间的结构,并为该参数提供默认值。这样,当/如果分配结构的额外时间不是问题时,用户可以调用该函数而无需传递结构,但如果(例如)构建一个可以从重复重用相同空间中受益的处理管道,则可以传递一个函数。