【发布时间】:2016-05-06 03:03:23
【问题描述】:
许多年前,(至少对我而言)静态 C++ 多态性似乎是一致的。 Python 等语言依赖于duck typing,你有:
def fn(foo, bar):
foo.baz(bar.bo())
这个想法是,如果它适当地“嘎嘎”,那么语言就可以了。
相反,在 C++ 中,您必须解释它是什么“动物”:
void fn(foo_type foo, bar_type bar);
对于“家庭王国”,您需要明确使用 template 关键字:
template<class Foo, class Bar>
void fn(Foo foo, Bar bar);
有了像auto ...() -> decltype 这样的新功能返回类型,尤其是generic lambdas,似乎有一些更像非模板Python 的鸭子类型:
[] (auto container) { return container.size(); };
那么,我的问题是,为什么仍然需要 template 关键字?为什么不完全接受(可选)鸭式打字:
// 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.
【问题讨论】:
-
你检查过 C++1z/C++2x 的概念提案吗?
-
@Yakk,谢谢-我没有关注概念的位置。会读起来。
-
它即将到来,但并非所有事情都同时发生。在 C++11 中,我们得到了 lambdas 的推导返回类型,然后在 C++14 中,我们得到了所有函数的返回类型。在 C++14 中,我们得到了泛型 lambda(即
auto参数),Concepts TS 为普通函数添加了相同的(这样的函数隐式成为函数模板并为提供的参数实例化)。 -
谢谢@JonathanWakely,这很有道理。
-
无论是
auto还是template,您都需要某种方式向编译器表明该声明不是具体的,而是通用的(参数化的)声明。这确实留下了将哪些名称作为参数的问题。
标签: c++ templates generics duck-typing