What's the relationship between C++ template and duck typing?

后端 未结 7 1977
一向
一向 2020-12-29 17:48

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?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 18:51

    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
        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++.

提交回复
热议问题