9

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.
Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • 5
    Have you examined the concepts proposals for C++1z/C++2x? – Yakk - Adam Nevraumont Jan 28 '16 at 16:22
  • @Yakk, thanks - I did not follow on where concepts are. Will read up. – Ami Tavory Jan 28 '16 at 16:24
  • 3
    It's coming, but not everything happens at once. In C++11 we got deduced return types for lambdas, then in C++14 we got them for all functions. In C++14 we got generic lambdas (i.e. `auto` parameters) and the Concepts TS adds the same for normal functions (such a function implicitly becomes a function template and gets instantiated for the supplied arguments). – Jonathan Wakely Jan 28 '16 at 16:44
  • Thanks, @JonathanWakely, that make sense. – Ami Tavory Jan 28 '16 at 16:51
  • 1
    Whether it's `auto` or `template`, you need some way to signal to the compiler that the declaration is not a concrete one, but a generic (parameterized) one. And that does leave the question which names are to be taken as parameters. – MSalters Jan 28 '16 at 21:07
  • Regardless, _some_ terms are going to have to have a consistent, instantiated type. You won't get full dynamic / duck typing as in Python by complicating the template system. You might get closer to something like Haskell's heavily inferred type system where you can define your ducks (typeclasses). – Alex Reinking Jul 31 '18 at 21:18

1 Answers1

11

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;
}
Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38