user1569115
user1569115

Reputation:

C++ compiler couldn't derive a right type from iterator

I have the following function:

template <typename Iterator> 
void merge(Iterator begin, Iterator middle, Iterator end) {
    std::vector<T> first(begin, middle), second(middle, end);

    auto i1 = first.begin();
    auto i2 = second.begin();

    while (begin != end) {
        if (i2 == second.end() || *i1 < *i2) {
            *begin = *i1;
            ++i1;
        } else {
            *begin = *i2;
            ++i2;
        }   
        ++begin;
    }   
}   

But when I try to use it:

int data[] = {1,2,3,4,5,6,7,8};
merge(data, data + 4, data + 8);

I get a error:

candidate template ignored: couldn't infer template argument 'T'

How can I define the merge function right without explicit specifying of the T type?

Upvotes: 0

Views: 102

Answers (2)

jrok
jrok

Reputation: 55425

How is compiler supposed to guess what T is? You neither provided any context to deduce it from nor did you explicitly tell it (in any case, T would need to be declared in template parameter list, like template<typename T, typename Iterator>).

I'd use iterator_traits here:

typedef typename std::iterator_traits<Iterator>::value_type T;
std::vector<T> first(begin, middle), second(middle, end);

Upvotes: 3

Qaz
Qaz

Reputation: 61970

Use std::iterator_traits to extract the type you need instead of having T being a template argument (which the error is really hinting at, despite your code):

std::vector<typename std::iterator_traits<Iterator>::value_type> first(begin, middle), second(middle, end);

Upvotes: 2

Related Questions