3 ms·
You can use duck typing (without losing the compile time type checking) in C++ using templates. Somehow they get a lot of bad press, but for me they're one of t
by gordaco 13y ago
You can use duck typing (without losing the compile time type checking) in C++ using templates. Somehow they get a lot of bad press, but for me they're one of the key features of C++.
- gizmo686 13y agoI've never worked with templates. Do they require you to write the function for use with templates, or can you use templates to pass an object into a function which was designed for another specific type of object. Based on my limited understanding of compilers, I do not see how you could efficiently implement duck typing without some type of JIT compiling.
- gordaco 13y agoThey require you to write the function for use with templates; as long as the callee is ready to use templates, you can pass anything that fits the interface needed. Everything is done at compile time. You can use a generic type as argument (template <typename T> void method(T arg) ), or a templated one (template <typename T> void method(MyObject<T> arg) ). In both cases the method will fail to compile if the body requires a missing field or method, but in the second one you get a standard "type mismatch" error, while in the first you'll get a "type X doesn't support method Y".