【问题标题】:pass "pointer to pointer" to a template function将“指针指针”传递给模板函数
【发布时间】:2016-06-01 07:34:17
【问题描述】:

我有一个为指针分配内存的函数,如下所示:

   void initializeImageBuffer(unsigned char **image, int w, int h)
   {
        if (*image != NULL)
            delete[] *image;
        *image = new unsigned char[w * h];
   }

现在我想使用函数模板来概括参数类型(无符号字符/整数/双精度)。这就是我所做的:

 template<typename T, int, int>
 void initializeImageBuffer(T **image, int w, int h)
   {
        if (*image != NULL)
            delete[] *image;
        *image = new T[w * h];
   }

但是使用如下函数会出错:

    unsigned char* image;
    initializeImageBuffer(&image, 200, 200);

“没有使用这些参数类型的重载函数实例。参数类型是 (unsigned char**, int, int)。”

【问题讨论】:

    标签: c++ function templates pointers


    【解决方案1】:
    template<typename T, int, int>
    

    在这里你声明你的模板有三个参数,类型T和两个未命名的ints。由于无法在调用站点推断 ints 的值,因此您需要显式提供它们以及 T,因为您只能从左到右提供模板参数:

    initializeImageBuffer<unsigned char, 42, 42>(&image, 200, 200);
    

    但是,您最可能想要的只是删除这些ints,它们在这里绝对没有用。

    template<typename T>
    void initializeImageBuffer(T **image, int w, int h)
    

    【讨论】:

      【解决方案2】:

      您可能会将模板参数与函数参数混淆。模板参数列表中的int, int在这里是不必要的,不能从函数调用中推断出来,这就是编译器报错的原因。

      删除它们:

      template<typename T>
      void initializeImageBuffer(T **image, int w, int h)
      {
          if (*image != NULL)
              delete[] *image;
          *image = new T[w * h];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-10
        • 2013-06-25
        相关资源
        最近更新 更多