C++: How can I create dynamic template type
c++
Solution
How about something like this:
template <typename U, typename T>
void transfer_mat(Mat & mat, T & t)
{
for (int i = 0, r = mat.rows; i != r; ++j)
{
for (int j = 0, c = mat.cols; j != c; ++j)
{
U src = mat.at<U>(i, j);
U dst = mat.at<U>(i, j);
t.transfer(src, dst);
}
}
}
Then you can say:
switch(channels)
{
case 1:
transfer_mat<uchar>(mat, t);
break;
case 2:
transfer_mat<Vec3b>(mat, t);
break;
}
Problem
I have the following piece of code, which I created for changing the intensity of a pixel in an OpenCV image (Cv::Mat class). As you can see, I'm looping in both cases, but with different template type. The 'transfer' function can be overloaded. My question is, therefore, how can I create dynamic template type so that it looks better .. ``` Mat mat = _mat.clone() ; int channels = mat.channels(); switch(channels) { case 1: for (int i=0; i<mat.rows; i++) { for (int j=0; j<mat.cols; j++) { uchar src = mat.at<uchar>(i,j); uchar dst = mat.at<uchar>(i,j); t.transfer(src, dst); } } break; case 3: for (int i=0; i<mat.rows; i++) { for (int j=0; j<mat.cols; j++) { Vec3b src = mat.at<Vec3b>(i,j); Vec3b dst = mat.at<Vec3b>(i,j); t.transfer(src, dst); } } break; } return mat ; ```