C ++ vector constructor creation context

I am trying to implement a vector container referenced at http://www.cplusplus.com/reference/vector/vector/vector/ . There are two constructors that cause some problems:

template <typename T>
vector (size_type n, const T& val);

template <typename T>
template <typename InputIterator>
vector (InputIterator first, InputIterator last);

      

When I use vector<int> vec(100, 1);

. It seems that both template constructors make instances. So I got template <typename T> vector (size_type n, const T& val)

with T = int and template <typename T> template <typename InputIterator> vector (InputIterator first, InputIterator last)

with T = int, InputIterator = int .

How to solve this?

+3


source to share


1 answer


Note that the standard (since C ++ 11) requires an overloaded constructor std::vector

that takes an iterator as a parameter to only participate in overload resolution when the passed arguments act as an iterator.

This overload is only involved in overload resolution if the InputIt satisfies the InputIterator , to avoid ambiguity with overload (2).

You can use SFINAE with std :: iterator_traits to do it for your own vector implementation. eg.

template <typename InputIterator, typename = typename std::iterator_traits<InputIterator>::value_type>
vector (InputIterator first, InputIterator last) { ... }

      



In case InputIterator = int

std::iterator_traits<int>

does not contain any member types such as value_type

then overloading will be excluded from overload resolution.


BTW: More precisely, the problem is not that "both template constructors are instantiated"; I'm not sure which type is size_type

in your implementation, if it is some other type, which int

for example std::size_t

then for vector<int> vec(100, 1);

the 1st overload will not be selected, because it is required to convert the 1st argument from int

to std::size_t

, then the second overload will be selected. because she can create the perfect combination with InputIterator = int

. This is not the behavior we expect.

+4


source







All Articles