Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 500
Thomson Avatar asked Aug 03 '11 07:08

Thomson


People also ask

Is C++ template duck typing?

No, this is a different concept. duck typing is a method to find out the type of a dynamic typed container. C++ templates aren't dynamic typed, they get instantiated with a specific type.

Does C# have duck typing?

Yes, you are right, but there is always some but. Even though C# is mostly strongly typed language (leaving aside the new keyword dynamic) there are some parts where the . NET uses duck typing instead of the traditional static strong type checking.

Which programing language uses duck typing?

What languages support duck typing? Python and Ruby support duck typing, both of which are dynamic typed languages. In general, dynamic typed languages such as JavaScript and TypeScript support duck typing.

Why is it called duck typing?

The name comes from the phrase, “If it walks like a duck and it quacks like a duck, then it must be a duck.” Duck typing is related to dynamic typing, where the type of the class of an object is going to be less important than the methods that it defines.


1 Answers

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.

like image 94
tgmath Avatar answered Oct 06 '22 01:10

tgmath