How to distinguish these two insert functions

Viewed 36

My own list has two insert functions

template<typename T, typename Allocator>
auto list<T, Allocator>::insert(iterator pos, size_t count, const T & value)->iterator
{
    for (size_t i = 0; i < count; i++) {
        pos = insert(pos, value);
    }
    return pos;
}


template<typename T, typename Allocator>
template<typename ...Args>
 auto list<T, Allocator>::insert(iterator pos, Args && ...args) -> iterator
{
     auto ret_val = this->get_allocator().allocate(1);
     this->get_allocator().construct(ret_val, std::forward<Args>(args)...);
     auto new_node = new node<T>(ret_val);
     auto current_node = pos.l_node;
     new_node->n_next = current_node;
     new_node->n_prev = current_node->n_prev;
     current_node->n_prev->n_next = new_node;
     current_node->n_prev = new_node;
     return iterator(new_node);
}

Sometimes the compiler does not know which function should be called,For example, the following situation

list<int> l1;
l1.insert(l1.begin(),10, 2);

I expect the first function to be called, but in fact the second function is called,Then the following error will appear The compiler cannot cast from initializer_list to int.

The code is here:https://paste.ubuntu.com/p/FxHPrdDHsj/

1 Answers

The second one is being called because it is a better match.

The first function wants three parameters (iterator, size_t, int).

The second function wants N parameters (iterator, stuff).

You're providing (iterator, int, int).

Matching the first function requires an implicit conversion (int -> size_t). Matching the second one requires no conversions.

Change the call to l1.insert(l1.begin(),(size_t) 10, 2) and it should call the first one.

Related