关于重载:c ++标准中的重载vs默认参数

overload vs default parameters in c++ standard

我正在读另一个问题,它让我思考。 通常,标准指定在其描述中具有默认参数的函数。 标准是否允许将这些作为重载写入?

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

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

标准库的符合实现可以实现这个,而不是像这样的两个函数吗?

1
2
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(); }测试。 微观优化,但你仍然看到了例子的重点。


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)说:

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 replacing a member function signature with default values by two or more member function signatures with equivalent behavior;

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

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