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

Thomson picture Thomson · Aug 3, 2011 · Viewed 9.9k times · Source

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?

Answer

tgmath picture tgmath · Aug 3, 2011

To me C++ templates are a compile-time version of duck typing. The compiler will compile e.g. Class and as long as your Duck has all needed types it will instantiate a class.

If something is not correct(e.g. copy constructor missing) the compilation fails. The counterpart in real ducktyping is a failure when you call a function with a non-duck type. And here it would occur at runtime.