Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does C++1* Still Need the template Keyword in Lieu of Full Duck Typing

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.
like image 953
Ami Tavory Avatar asked Jan 28 '16 16:01

Ami Tavory


People also ask

When to use template keyword?

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 .

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.

What is meant by duck typing in Python?

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.


1 Answers

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;
}
like image 176
Yam Marcovic Avatar answered Nov 02 '22 21:11

Yam Marcovic