C ++标准中的重载与默认参数 [英] overload vs default parameters in c++ standard

查看:80
本文介绍了C ++标准中的重载与默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读另一个问题,这让我开始思考.该标准通常会指定在其描述中具有默认参数的功能.标准是否允许将它们写为重载?

I was reading another question, and it got me thinking. Often the standard specifies functions which have default parameters in their descriptions. Does the standard allow writing these as overloads instead?

例如,标准说std::basic_string::copy具有以下声明:

For example, the standard says that std::basic_string::copy has the following declaration:

size_type copy(Ch* p, size_type n, size_type pos = 0) const;

标准库的符合要求的实现可以将其实现为像这样的两个函数吗?

Could a conforming implementation of the standard library implement this instead as two functions like this?

size_type copy(Ch* p, size_type n, size_type pos) const;
size_type copy(Ch* p, size_type n) const;

在此示例中,第二个版本可以跳过第一个版本中必需的if(pos > size()) { throw out_of_range(); }测试.进行了微优化,但您仍然可以看到示例的要点.

In this example, the second version could skip the if(pos > size()) { throw out_of_range(); } test that is necessary in the first one. A micro-optimization, but still you see the point of the example.

推荐答案

标准库的符合要求的实现可以将其实现为像这样的两个函数吗?

Could a conforming implementation of the standard library implement this instead as two functions like this?

是的. C ++标准(C ++ 03 17.4.4.4/2-3)表示:

Yes. The C++ Standard (C++03 17.4.4.4/2-3) says:

实现可以在[Standard Library]类中声明其他非虚拟成员函数签名:

An implementation can declare additional non-virtual member function signatures within a [Standard Library] class:

-通过将具有默认值的参数添加到成员函数签名中;但是,相同的纬度不能扩展到虚拟,全局或非成员函数的实现.

-- by adding arguments with default values to a member function signature; the same latitude does not extend to the implementation of virtual or global or non-member functions, however.

-通过将具有默认值的成员函数签名替换为具有相同行为的两个或多个成员函数签名;

-通过为成员函数名称添加成员函数签名来实现.

-- by adding a member function signature for a member function name.

对C ++标准库中描述的成员函数签名的调用的行为与实现声明没有声明其他成员函数签名的行为相同

A call to a member function signature described in the C + + Standard library behaves the same as if the implementation declares no additional member function signatures

这篇关于C ++标准中的重载与默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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