1
template<typename T, typename TriFunc>
TriFunc process_three_continuous_channels_impl(cv::Mat &input, TriFunc func)
{
    int const total = input.total();
    auto *input_ptr = input.ptr<T>(0);
    for(int index = 0; index != total; ++index){
        func(*input_ptr, *(input_ptr + 1), *(input_ptr + 2));
        input_ptr += 3;
    }

    return func;
}

/**
 * overload, haven't find a good solution to reduce redundancy codes yet
 */
template<typename T, typename TriFunc>
TriFunc process_three_continuous_channels_impl(cv::Mat const &input, TriFunc func)
{       
    int const total = input.total();
    auto const *input_ptr = input.ptr<T>(0);
    for(int index = 0; index != total; ++index){
        func(*input_ptr, *(input_ptr + 1), *(input_ptr + 2));
        input_ptr += 3;
    }

    return func;
}

我想减少冗余码但找不到好的解决方案

template<typename T, typename TriFunc>
TriFunc process_three_continuous_channels_impl(cv::Mat const &input, TriFunc func)
{
   return process_three_continuous_channels_impl<T>(const_cast<cv::Mat&>(input, func));
}

这是行不通的,因为在 const_cast 将非常量 cv::Mat 转换为 const 之后,func 将能够更改输入的数据也不起作用,这样 func 将无法更改数据的输入。有什么建议么?

4

2 回答 2

1

您可以使cv::Mat参数成为对模板参数类型的引用。

template<typename Mat, typename T, typename TriFunc>
TriFunc process_three_continuous_channels_impl(Mat&& input, TriFunc func)
{
    int const total = std::forward<Mat>(input).total();
    auto input_ptr = std::forward<Mat>(input).template ptr<T>(0);
    for(int index = 0; index != total; ++index){
        func(*input_ptr, *(input_ptr + 1), *(input_ptr + 2));
        input_ptr += 3;
    }

    return func;
}
于 2013-07-30T09:19:19.483 回答
1

如果 C++11 适合您,那么完美的转发在这里工作:

template <typename T, typename TriFunc>
TriFunc wrapper(cv::Mat && input, TriFunc func)
{
    return process_three_continuous_channels_impl<T>(
        std::forward(input), func);
}
于 2013-07-30T09:18:13.347 回答