infoclogged
infoclogged

Reputation: 3997

How to pass const_iterator and non const iterator in a single template call

I would like to know how to pass a const_iterator to a template. For example in the below call and function template.

The iterator for first1 and last 1 is

std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::iterator

and the iterator for first2 and last2 is const_iterator

std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::const_iterator

template < typename T>
T my_function(T __first1, T __last1, T __first2, T __last2, T __result)
{

}

Call is

my_function(co1.begin(), co1.end(), co2.begin(), co2,end(), result.begin());

Is there a way to pass both a normal iterator and a const_iterator in a single template?

The error is

error: no matching function for call to ‘my_function(std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::iterator, std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::iterator, std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::const_iterator, std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::const_iterator, std::vector<std::pair<cv::Point_<float>, cv::Point_<float> > >::iterator)’’
             my_function(co1.begin(), co1.end(), co2.begin(), co2.end(), result.begin());

Upvotes: 1

Views: 209

Answers (2)

LogicStuff
LogicStuff

Reputation: 19607

Obviously, you need different types so that deduction succeeds, not just T:

template <typename T1, typename T2>
T1 my_function(T1 __first1, T1 __last1, T2 __first2, T2 __last2, T1 __result) { ... }

You can add a SFINAE check (advanced!) (whichever way you want):

std::enable_if_t<std::is_convertible_v<T2, T1>> // C++17 way

to preserve the restriction that T2 is only a const version of T1. You might want to add a separate type for _result and the return type as well.

Upvotes: 5

NathanOliver
NathanOliver

Reputation: 180435

Instead of trying to convert one iterator type to another just add another template type that will allow the two ranges to have two different types of iterators.

template < typename T, typename U, typename O>
T my_function(T __first1, T __last1, U __first2, U __last2, O __result)
{

}

added a third type for the output type as well

This makes the function much more generic and flexible.

Upvotes: 4

Related Questions