问题描述
考虑以下函数原型:
void Remove(SomeContainer& Vec, const std::size_t Index);
SomeContainer Remove(SomeContainer Vec, const std::size_t Index);
第二个是根据第一个实现的.也就是说,除了一个是按引用传递,另一个是按值传递之外,它们在各个方面的功能都是相同的.
The second is implemented in terms of the first. That is to say, they are functionally identical in every way except that one is pass-by-reference and the other is pass-by-value.
然而,GCC 表示这些在这种情况下是模棱两可的,即使第一种形式是唯一不返回值的形式:
However, GCC says these are ambiguous in cases like this, even though the first form is the only one that does not return a value:
Remove(SomeContainer, 123);
是否有任何解决方法,或者我是否必须为每个表单想出不同的名称?
Is there any workaround to this, or do I have to come up with different names for each form?
推荐答案
返回类型不是函数重载的基础.
函数的重载只能符合以下条件之一:
Return type is not an basis of function overloading.
Overloading of functions can only be with one of the following criteria:
- 没有参数
- 参数类型 &
- 参数序列
调用者可以忽略返回类型,因此它不是函数重载的有效标准.
The return type can be ignored by the caller and hence it is not a valid criteria for function overloading.
综上所述,传值和传引用都会给编译器造成歧义.例如:
Having said the above, pass by value and passing a Reference will create a ambiguity to the compiler. For eg:
void doSomething(int i)
{
}
void doSomething(int &i)
{
}
int main()
{
int val = 10;
doSomething(val); //Ambiguous
}
此处编译器无法确定将val
传递给哪个版本的doSomething()
.它可以对任何版本进行有效的函数调用,因此它会在编译时寻求帮助(因为这是静态链接)并将调用标记为不明确.
Here the compiler cannot determine as to pass val
to which version of doSomething()
. It can make a valid function call to any of the versions, so it cries out for help at compile time(since this is static linking) and flags the calls as ambiguous.
如果像你这样.重命名函数或传递指针参数是一种选择/偏好,这将使两个函数重载(名称相同但参数类型不同).然而,重要的是要考虑到要求 &功能在选择首选项时将执行的操作.就个人而言,我不会为了重载而选择指针.如果我确实需要重新设置或使我的参数指向不同的变量,那么选择指针参数是有意义的.
In case such as yours. It is a choice/preference as to rename the functions or pass pointer argument which will make the two functions overloaded(same name but different argument types). However, it is important to take in to account the requirement & the action the function is going to perform while choosing the preference. Personally, I wouldn't choose a pointer just for sake of overloading. If I do need to reseat or make my argument point to different variables then it would make sense to choose pointer argument.
简单的方法是只有两个不同的函数名称.没有任何开销,而且与任何其他函数调用一样高效.
Simple way is to just have two distinct function names. There is no overhead and it is just as efficient as any other function call.
这篇关于函数的不明确引用/值版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!