C ++模板和鸭式键入之间的关系是什么? [英] What's the relationship between C++ template and duck typing?

查看:146
本文介绍了C ++模板和鸭式键入之间的关系是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,C ++模板使用了鸭式打字的想法,是吗?是否意味着模板类或方法中引用的所有泛型类型都是鸭式?

To me, C++ template used the idea of duck typing, is this right? Does it mean all generic types referenced in template class or method are duck type?

推荐答案


,C ++模板使用了鸭式打字的想法,是不是?

To me, C++ template used the idea of duck typing, is this right?

不,C ++模板用于实现通用代码。也就是说,如果你有可以使用多个类型的代码,你不必为每个类型重复它。例如 std :: vector std :: list 就是这个行为的明显例子。 C + +模板已被滥用进行其他操作,但通用性是最初的用意。

No, C++ templates are used to implement generic code. That is, if you have code that can work with more than one type, you don't have to duplicate it for each type. Things like std::vector and std::list are obvious examples of this in action. C++ templates have been abused into doing other things, but genericity was the original intention.


是否意味着在模板类或方法
中引用的所有类型都是鸭子类型?

Does it mean all generic types referenced in template class or method are duck type?

不,它们只是正常类型,就像C ++中的其他类型一样。它们只是在模板实际被实例化之前才知道。

No, they are just "normal" types just like every other type in C++. They are just not known until the template is actually instantiated.

但是,模板可以用来实现像迭代器就是一个例子。考虑这个函数:

However, templates can be used to implement something like duck typing. Iterators are an example. Consider this function:

template<class InputIterator, class OutputIterator>
    OutputIterator copy(InputIterator first, InputIterator last,
                        OutputIterator result)
{
    while (first!=last) *result++ = *first++;
    return result;
}

注意 copy 函数可以接受任何类型的参数,因为它实现了不等式运算符,取消引用运算符和后缀增量运算符。这可能就像你在C ++中得到的鸭式输入一样。

Note that the copy function can accept arguments of any type, as along as it implements the inequality operator, the dereference operator, and the postfix increment operator. This is probably as close to duck typing as you'll get in C++.

这篇关于C ++模板和鸭式键入之间的关系是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆