如何使用仿函数为自定义容器创建通用插入函数

时间:2013-01-17 14:34:35

标签: c++ c++03

此时,我并不担心这是我的问题的正确解决方案(实际上,它不是)但我遇到了这个问题,我无法解决它所以它一直困扰着我和我不能放手。

我有POD类型的通用容器。这个容器可以通过不初始化内存而不出于性能原因调用任何构造函数或析构函数来避免复制,以换取使用户对此负责(这不是pods和我们的用例那么大的问题)。

这是一个关于如何使用它的非常简单的演示。

template <typename Pod_Type>
class PodContainer
{
public:
   //stl-like iterators for compatibility with stl-algorithms
   Pod_Type* begin();
   Pod_Type* end();
   //special "insertion" function that inserts a non-initialized pod
   Pod_Type* new_empty();

   //This "something" is my problem. I guess this has to be a functor. 
   //More on this later
   Something generic_insert;

private:
    Pod_Type* mStorage; //Allocated space for pods
};

//Simple structure to use as example
struct PodA
{
   int x,y,z;
};

//Function to initialize a pod of type podA with the given params
inline
init_podA( podA* ptr, int a, int b, int c) 
{
   ptr->x = a; ptr->y = b; ptr->z = c;
}


int main()
{
  //Create a buffer
  PodContainer<podA> buff;

  //Insert some elements and intialize them "by hand"
  for (int i=0; i < 10 ; ++i)
  {
     init_podA( buff.new_empty(), 1,2,3);
  }
}

请注意,容器类的所有内存管理问题都已解决(我已经对其进行了广泛的测试),容器本身非常适合我的实际问题。

现在为有趣的部分。我想让这个“东西”从容器中的里面调用我的init_podA函数。显然我不能在Buffer类中硬连接这个,因为我甚至不知道用户需要多少个参数才能获得他的pod类型所需的下一个init_xxx函数。我开始考虑将第二个参数模板传递给PodContainer类,其中第二个是traits类,我可以查询包含调用真实初始化函数的仿函数。在PodContainer类中,我可以查询traits类并保存将在那里构造的仿函数,这些仿函数将由用户调用并给人一种成员函数的印象。

我的想法是,我将使用这样的特征:

template<typename PodType, typename PodTraits = MyPodTraits<PodType> >
class PodContainer
{
 PodContainer():
      generic_insert(PodTraits::get_inserter(this))
 //The rest of the PodContainer definition
 ....    

//And the user of the container would see this
PodContainer<PodA> buffer;
buffer.generic_insert(a,b,c); //Calls buffer->new_empty and initializes a pod

这甚至可能吗?我想我会使用一些boost :: bind技巧,我是对的吗?算子的类型是什么,所以我可以在容器中收到它?有更好的选择吗?

谢谢!

编辑:请注意,我不能使用c ++ 11 :(

1 个答案:

答案 0 :(得分:0)

只要您不能使用C ++ 11(和可变参数模板),您就可以随时努力并为每个可能数量的参数提供重载。像这样:

void generic_insert(void (*init)(PodType*)) { init(new_empty()); }

template<typename A1>
void generic_insert(void (*init)(PodType*, A1), A1 a1) { init(new_empty(), a1); }

/* and so on ... */