问题
I'm writing a class template like stl vector,and two constructors are like this:
template<class T>
vector<T>::vector(size_t count, const T&value) :bg(new T[count]),
ed(bg + count), cap(ed) {
for (auto it = bg; it != ed; ++it)
*it = value;
}//bg ed cap are all T*
template<class T>
template<class Input>
vector<T>::vector(Input first, Input second) : bg(new T[second - first]),
ed(bg + (second - first)), cap(ed) {
memcpy(bg, (void*)first, sizeof(T)*(second - first));
}
so if I do this
vector<int>v(2,0)
complier gives me error,it seems like the program uses the second constructor instead of the first. can anyone explain why? the stl vector says
This overload only participates in overload resolution if InputIt satisfies LegacyInputIterator, to avoid ambiguity with the overload (3).
so how can I change my code to avoid this? thanks in advance.
回答1:
The second overload is chosen because it better matches the argument types when Input
is int
. Specifically, given the arguments (int, int)
, the overload (int, int)
is a better match than the overload (size_t, int const&)
. Note that if you change the first parameter of the first overload from size_t
to int
, it will be chosen instead.
If you want to disable the function template overload when Input
is an input iterator, you can exploit SFINAE using std::enable_if:
template <
typename InputIt,
typename = std::enable_if_t<
std::is_base_of_v<
std::input_iterator_tag,
typename std::iterator_traits<InputIt>::iterator_category>>>
vector(InputIt, InputIt)
{
}
You can optionally extract the logic out into a type trait.
template <typename T, typename = void>
struct is_input_iterator : std::false_type
{
};
template <typename T>
struct is_input_iterator<T, std::void_t<typename std::iterator_traits<T>::iterator_category>>
: std::is_base_of<
std::input_iterator_tag,
typename std::iterator_traits<T>::iterator_category>
{
};
template <typename T>
constexpr bool is_input_iterator_v = is_input_iterator<T>::value;
Then the function definition becomes a bit more readable.
template <
typename InputIt,
typename = std::enable_if_t<is_input_iterator_v<InputIt>>>
vector(InputIt, InputIt)
{
}
来源:https://stackoverflow.com/questions/58646533/class-template-constructor-overload-resolution-ambiguity