Many years ago, (at least for me,) static C++ polymorphism seemed coherent. Languages such as Python relied on duck typing, where you have:
def fn(foo, bar):
foo.baz(bar.bo())
and the idea was that if it "quacked" appropriately, it was fine by the language.
In C++, conversely, you'd have to explain what "animal" it was:
void fn(foo_type foo, bar_type bar);
and for "kingdoms of families", you'd explicitly need to use the template
keyword:
template<class Foo, class Bar>
void fn(Foo foo, Bar bar);
With new features like auto ...() -> decltype
return types, but especially generic lambdas, there appears to be something much more like non-template Python-like duck typing:
[] (auto container) { return container.size(); };
My question, then, is why is the template
keyword still needed? Why not just fully embrace (optional) duck typing:
// Takes a foo_type and a bar_type
void fn(foo_type foo, bar_type bar);
// Takes some "foo-quacking" type, and a bar_type
void fn(auto foo, bar_type bar);
// Etc.
The "template" keyword It uses the less-than operator to compare boost::function against zero ( int() ), and then uses the greater-than operator to compare the resulting bool against f .
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.
Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.
It's actually almost at the door as part of the Concepts feature, and some compilers already implement it! For example, with GCC 4.9, if you specify -std=c++1y
, you can actually compile and run the following:
auto print_arg(auto arg) {
std::cout << arg;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With