To me, C++ template used the idea of duck typing, is this right? Does it mean all generic types referenced in template class or method are duck type?
To me, C++ template used the idea of duck typing, is this right?
No, C++ templates are used to implement generic code. That is, if you have code that can work with more than one type, you don't have to duplicate it for each type. Things like std::vector
and std::list
are obvious examples of this in action. C++ templates have been abused into doing other things, but genericity was the original intention.
Does it mean all generic types referenced in template class or method are duck type?
No, they are just "normal" types just like every other type in C++. They are just not known until the template is actually instantiated.
However, templates can be used to implement something like duck typing. Iterators are an example. Consider this function:
template<class InputIterator, class OutputIterator>
OutputIterator copy(InputIterator first, InputIterator last,
OutputIterator result)
{
while (first!=last) *result++ = *first++;
return result;
}
Note that the copy
function can accept arguments of any type, as along as it implements the inequality operator, the dereference operator, and the postfix increment operator. This is probably as close to duck typing as you'll get in C++.