Duck typing is completely orthogonal to dynamic typing - you can have static duck typing. C++ templates are one well-known example, but OCaml's intersection of its OO system with type inference also makes it kinda duck typed - e.g. if you define a function that calls a method on an argument, the type of argument is inferred as "some object that has a method with such-and-such name and types". If you call another method, that also gets added etc. But it's still statically typed - at call site, the actual type of the argument must have those methods, or it won't compile.
Or, getting back to C++, we have polymorphic lambdas there now (which are implemented in terms of templates, but with syntactic sugar that makes it all much cleaner):
auto f = [&](auto x, auto y) {
return x + y;
};
cout << f(1, 2); // 3
cout << f("a"s, "b"s); // "ab"
cout << f("abcd", 2); // "cd"
cout << f(main, true); // compile-time error
Again, all statically typed, although the type checking basically consists of substituting the types in the body and checking if the result makes sense. Which is to say, the error messages from such code are very similar to the ones you get in e.g. Python if you have the types wrong, except here the errors are compile-time, not runtime.
The Agg C++ library defines every class as a template, taking duck-typed parameters:
- type of Agg object passed into object
- type of "algorithm" used (or similar)
I read matplotlib's Agg C++ backend. Guessing which Class A could be passed into various template parameters in Class B was miserable because of duck typing. And it also broke "jump to definition".
```
Class B<A> {
A a;
}
this->a.foo(), but you don't know what type a is.
```
Or, getting back to C++, we have polymorphic lambdas there now (which are implemented in terms of templates, but with syntactic sugar that makes it all much cleaner):
Again, all statically typed, although the type checking basically consists of substituting the types in the body and checking if the result makes sense. Which is to say, the error messages from such code are very similar to the ones you get in e.g. Python if you have the types wrong, except here the errors are compile-time, not runtime.