简体   繁体   English

C ++歧义重载问题

[英]C++ ambiguity overloading problem

I have a class called FileProc that runs File IO operations. 我有一个名为FileProc的类,它运行文件IO操作。 In one instance I have declared two functions (which are sub-functions to operator= functions), both decisively different: 在一个实例中,我声明了两个函数(它们是operator =函数的子函数),两者在决定性方面是不同的:

const bool WriteAmount(const std::string &Arr, const long S)
{
    /* Do some string conversion */
    return true;
}

const bool WriteAmount(const char Arr[], unsigned int S)
{
    /* Do some string conversion */
    return true;
}

If I make a call with a 'char string' to WriteAmount, it reports an ambiguity error - saying it is confused between WriteAmount for char string and WriteAmount for std::string. 如果我用'char string'调用WriteAmount,则会报告歧义错误-表示在char string的WriteAmount和std :: string的WriteAmount之间是混淆的。 I know what is occurring under the hood - it's attempting to using the std::string constructor to implicitly convert the char string into a std::string. 我知道幕后发生的事情-它正在尝试使用std :: string构造函数将char字符串隐式转换为std :: string。 But I don't want this to occur in the instance of WriteAmount (IE I don't want any implicit conversion occurring within the functions - given each one is optimised to each role). 但是我不希望在WriteAmount实例中发生这种情况(即,我不希望函数内发生任何隐式转换-鉴于每个函数都针对每个角色进行了优化)。

My question is, for consistency, without changing the function format (IE not changing number of arguments or what order they appear in) and without altering the standard library, is there anyway to prevent implicit conversion in the functions in question? 我的问题是,为了保持一致性,在不更改函数格式的情况下(即,在不更改参数数量或它们以什么顺序出现的情况下)并且在不更改标准库的情况下,是否有任何方法可以防止所涉及函数的隐式转换?

I forgot to add, preferably without typecasting, as this will be tedious on function calls and not user friendly. 我忘了添加,最好不要添加类型转换,因为这在函数调用上是乏味的,并且对用户不友好。

You get the ambiguity because your second parameter is different. 因为第二个参数不同,所以您会产生歧义。 Trying to call it with long x = ...; WriteAmount("foo", x) 试图用long x = ...; WriteAmount("foo", x)来调用它long x = ...; WriteAmount("foo", x) long x = ...; WriteAmount("foo", x) will raise an ambiguity because it matches the second argument better with the first overload, but the first argument is matched better with the second overload. long x = ...; WriteAmount("foo", x)将引起歧义,因为它与第一个重载更好地匹配第二个参数,但是第一个重载与第二个过载更好地匹配。

Make the second parameter have the same type in both cases and you will get rid of the ambiguity, as then the second argument is matched equally worse/good for both overloads, and the first argument will be matched better with the second overload. 在两种情况下,使第二个参数具有相同的类型,您将摆脱歧义,因为第二个参数对于两个重载均匹配差/好,并且第一个参数与第二个重载匹配得更好。

Can't you change the second argument and cast it to unsigned int ? 您不能更改第二个参数并将其强制转换为unsigned int吗? It should not be able to use the first function call. 它应该不能使用第一个函数调用。 I have not coded in C++ for ages.. 我很久没有用C ++编写代码了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM