获取已在模板中延迟的类型

Get type that already was deferred in template

本文关键字:延迟 类型 获取      更新时间:2023-10-16

我创建了一个模板化类,它工作正常:

(我正在使用 openCV 库,所以我有 cv::Mat 类型的矩阵)

template < class T, T V >
class MatFactory
{
  private:
    const T static VALUE = V;
  public:
    void create(/* some args */)
    {
      cv::Mat M;
      // filling the matrice with values V of type T
      // loop i,j
      M.at<T>(i,j) = V;
      return M;
    }
};

但是在后面的代码中,我需要在某些索引(i,j)上获取矩阵M的元素。但是我怎么知道T型呢?

MatFactory<int, 1> MF;
// getting object
cv::Mat m = MF.create();
// then I need to get some value (with `.at<>` method)
int x = m.at<int>(2,3);
// But, it means I should every time explicitly declare INT type
// Can I somehow get the type, that was passed to template factory
// Than i'll write something like this:
T x = m.at<T>(2,3);
// How to get T from the deferred template?

只需将type成员添加到您的MatFactory

template <typename T, T V>
class MatFactory {
public:
    typedef T type;
   ...
};

请注意,非类型模板参数相当有限。特别是不允许使用浮点类型(考虑到这一点,这可能已通过 C++2011) 进行了更改)。

如果您知道数组元素类型(可以使用方法 Mat::type() 检索),则可以访问二维数组的元素 M_{ij}

M.at<double>(i,j) += 1.f;

假设 M 是双精度浮点数组。对于不同数量的维度,该方法有几种变体。

http://docs.opencv.org/modules/core/doc/basic_structures.html#mat