Search code examples
c++c++20duck-typingc++-concepts

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


There was an earlier question (8 years ago!) about the relationship between templates and duck typing here: What's the relationship between C++ template and duck typing? I've borrowed and modified the tag line for my question on a new feature of C++.

With C++20 there will be the new feature of "concept" that looks much more like a duck-typing feature. Is it correct that the new C++ "concept" is equivalent to duck typing for C++? If not, how is it different?


Solution

  • With C++20 there will be the new feature of "concept" that looks much more like a duck-typing feature

    Not really.

    1. If we accept that templates are already compile-time duck typing

      • I disagree with both the accepted answer on the linked question and the Wikipedia page, because doing the same thing at compile time instead of run time is not a persuasive reason to give it a wholly different name. See static vs. dynamic polymorphism for example.

      • then concepts are not obviously more duck-type-y than templates already are

      • the other argument here is that duck typing generally supposes you express your type constraints by attempting to use the type. Concepts are further from this model than templates already are.

    2. If we agree (wrongly) with both the accepted answer on the linked question, and with Wikipedia, then

      • the reason templates are not (an example of) duck typing is that they happen at compile time

      • concepts also happen at compile time

      • QED

    Concepts take what templates already do (which may or may not be, but definitely is, duck typing) and give finer-grained options for specialization, and/or more clearly express type constraints, and (hopefully) help to generate better errors.

    The quality of duckiness is invariant under all these operations.