有人可以解释这个函数重载解析度是如何模棱两可的吗?
鉴于:
/// This type *contains* a @c T.
template< typename T >
class User_Type
{
public:
/// This <em>conversion constructor</em> is a key part of it's API;
/// it won't likely change.
User_Type( T const & ar_data )
: m_data( ar_data )
{}
private:
T m_data;
};
/// @c some_value is just a templated function that generates a @c T.
template< typename T > T some_value();
template<> char some_value();
template<> int some_value();
/// This overloaded, non-templated function represents some third-party
/// code somewhere else; it's API can't be changed.
void other_function( User_Type< char > const& );
void other_function( User_Type< int > const& );
/// This is user-code. It's contents exercise some aspect of the 'User_Type' API.
/// This code can change.
template< typename T >
void function()
{
other_function( some_value< T >() ); /* AMBIGUOUS CALL */
User_Type< T > user_var = some_value< T >(); /* UNAMBIGUOUS CONVERSION */
other_function( user_var ); /* UNAMBIGUOUS CALL */
}
template void function< char >();
template void function< int >();
并使用进行编译g++-4.9 -Wall -Wextra
,我收到以下错误:
In instantiation of ‘void function() [with T = char]’:
error: call of overloaded ‘other_function(char)’ is ambiguous
note: candidates are:
note: void other_function(const User_Type<char>&)
note: void other_function(const User_Type<int>&)
In instantiation of ‘void function() [with T = int]’:
error: call of overloaded ‘other_function(int)’ is ambiguous
note: candidates are:
note: void other_function(const User_Type<char>&)
note: void other_function(const User_Type<int>&)
我希望最好的比赛other_function( char )
是other_function( User_Type< char > const& )
,最好的比赛other_function( int )
是other_function( User_Type< int > const& )
。
我了解必须为的每个参数进行类型转换other_function
。我预计char
到User_Type< char >
是一个更好的选择,而不是char
到User_Type< int >
,这可能是被允许char
到int
推广。我预计int
到User_Type< int >
是一个更好的选择,而不是int
到User_type< char >
,这可能是被允许int
到char
转换。
另外,如果我User_Type< T > user_var
从创建本地T
,那么我可以明确地致电other_function( user_var )
。从语义上讲,这应该等效于第一个原始语句。
由于没有与other_function(char)
或的完全匹配other_function(int)
,
other_function( some_value< T >() );
必须隐式转换其参数以匹配以下之一:
void other_function( User_Type< char > const& );
void other_function( User_Type< int > const& );
但是User_Type<char>
有ctorUser_Type<char>( char const& )
接受一个int
,并且User_Type<int>
有ctorUser_Type<int>( int const& )
接受一个char
。
您的转换属于“用户定义的转换顺序”的排名,并且由于这两种转换都是可能的,因此两者均包含在具有相同排名的过载集中。因此,通话是不明确的。(有关更多信息,请参见13.3.3.2在标准中对隐式转换序列进行排名。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句