函数重载与函数模板 - C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12331655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:10:03  来源:igfitidea点击:

function overloading vs function templates - C++

c++templatesoverloading

提问by kushalvm

In books on C++, why are we taught to use function overloadingwhen we have templatesat our disposal in C++?

在有关 C++ 的书籍中,为什么当我们在 C++ 中有可供使用的模板时,我们会教导我们使用函数重载

Wouldn't it be better to show the effective (and correct) use of templates? As opposed to where function overloading is taught in most books on C++?

展示模板的有效(和正确)使用不是更好吗?与大多数 C++ 书籍中教授函数重载的地方相反?

Or, are there good reasons to use one instead of the other?

或者,是否有充分的理由使用一种而不是另一种?

采纳答案by juanchopanza

Templates provide an advantage when you want to perform the same action on types that can be different. A simple example:

当您想对可能不同的类型执行相同的操作时,模板提供了一个优势。一个简单的例子:

template <typename T>
T foo(const T& a, const T& b) { return a + b; }

You can use overloading when you want to apply different operations depending on the type:

当您想根据类型应用不同的操作时,可以使用重载:

struct Foo{ void foo() const {} };

void foo(int i) { std::cout << "i = " << i << "\n"; }
void foo(const Foo& f) { f.foo(); }

You could achieve the above using templates and template specializations, but such specializations should represent a few exceptions to the general case.

您可以使用模板和模板特化来实现上述目的,但此类特化应该代表一般情况的一些例外。

回答by Puppy

Templates cannot take varying numbers of arguments. Overloads can. In addition, a template indicates that you can operate on any data type, but it's pointless to represent this when in fact, the vast, vast majority of templates would be specializations only (in your system). Also, overloads can be virtualand template specializations cannot. Nor can specializations differ in their signatures from the base.

模板不能接受不同数量的参数。超载可以。此外,模板表明您可以对任何数据类型进行操作,但实际上表示这一点毫无意义,绝大多数模板只是特化(在您的系统中)。此外,重载可以virtual,模板特化不能。专业化的特征也不能与基础不同。

template<typename T> void foo(T& t);
template<> void foo<std::string>(std::string* ptr); // Illegal
void foo(std::string* ptr); // Legal

This would severely constrain what kinds of overload you could produce compared to the current system.

与当前系统相比,这将严重限制您可以产生的过载类型。

回答by Mike Corcoran

You generally use templates when you want to do the same set of operations on many different data types.

当您想对许多不同的数据类型执行相同的一组操作时,通常会使用模板。

You generally would use function overloading when you want to do different operations on certain sets of data.

当您想对某些数据集执行不同的操作时,通常会使用函数重载。

the advantage of templates in a situation where you want to do the same set of operations on many different data types, is that the compiler will handle for you at compile time any possible new type you may create in the future that uses the templated function. if you were to use function overloading, you'd have to create a new function overload every time you created a new type that you wanted to pass to the specific function.

在您希望对许多不同的数据类型执行相同操作集的情况下,模板的优势在于编译器将在编译时为您处理您将来可能创建的使用模板化函数的任何可能的新类型。如果要使用函数重载,则每次创建要传递给特定函数的新类型时都必须创建新的函数重载。

回答by Vlad

Just an addition to juanchopanza's answer:

只是对 juanchopanza 的回答的补充:

With function overloads you can also vary the number of arguments, which can be handy.

通过函数重载,您还可以改变参数的数量,这很方便。

A simple example, if you have some function with the following declaration:

一个简单的例子,如果你有一些带有以下声明的函数:

void foo(int i, int j);

But you often call foo with first argument 0, you could write the following function which saves you some typing.

但是您经常使用第一个参数 0 调用 foo,您可以编写以下函数来节省一些输入。

void foo(int j) {
  foo(0, j);
}

回答by Jerry Coffin

Templates (normally) require that you use identical syntaxto carry out the operations on all (supported) types.

模板(通常)要求您使用相同的语法对所有(支持的)类型执行操作。

Function overloading is (or should be) used similarly, but allows you to use differentsyntax to carry out the operations for different types. That is to say that (although you don't have to) you can represent the values in different ways. One obvious example would be what are called atanand atan2in the C library. With atan, we pass the ratio of the "rise to the "run", and we get back the angle that ratio represents. With atan2we pass the values for the rise and run separately (which computes roughly the same result, but since it's given slightly more input data, can produce a more complete result as well).

函数重载是(或应该)类似地使用,但允许您使用不同的语法来执行不同类型的操作。也就是说(尽管您不必)可以用不同的方式表示值。一个明显的例子是所谓的atanatan2在C库。使用atan,我们传递“上升到“运行”的比率,我们得到比率代表的角度。atan2我们分别传递上升和运行的值(计算大致相同的结果,但因为它稍微给出了更多的输入数据,也可以产生更完整的结果)。

Although these are implemented as entirely separate functions in C, if they were written in C++ from the beginning it would be entirely appropriate to use a single name (e.g., atan) overloaded for both a one and two parameters:

尽管这些是在 C 中作为完全独立的函数实现的,但如果它们从一开始就用 C++ 编写,那么使用一个名称(例如,atan)重载一个和两个参数是完全合适的:

double atan(double);           // equivalent to current atan
double atan(double, double);   // equivalent to current atan2

Templates (short of specialization, which is pretty much just overriding what templates themselves provide) doesn't provide for differences in calling syntax like this.

模板(缺乏专业化,几乎只是覆盖了模板本身提供的内容)并没有提供这样的调用语法差异。

Overloading is also more constrained -- you provide one overload for each specific type you want to support (though if you take a pointer or reference those can also support derived types). With templates, a single template can (at least potentially) apply to anytype.

重载也受到更多限制——您为要支持的每种特定类型提供一个重载(尽管如果您采用指针或引用,这些也可以支持派生类型)。使用模板,单个模板可以(至少可能)适用于任何类型。

回答by Ritik Kamboj

So both overloadingand templatehave their equal use .

因此,无论overloading并且template有自己的平等使用。

one line differenceto about them is:

difference关于他们的一行是:

overloadingis used when we have various functions , doing SIMILARoperations .

overloading当我们有各种功能,做SIMILAR操作时使用。

templateis used when we have various functions , doing IDENTICALoperations .

template当我们有各种功能,做IDENTICAL操作时使用。

There is very big differnce between "SIMILAR" and "IDENTICAL".

There is very big differnce between "SIMILAR" and "IDENTICAL".