قالب غامض، وقانون المحارب
-
06-07-2019 - |
سؤال
والتعليمة البرمجية التالية يجمع في Visual C ++ ودول مجلس التعاون الخليجي، لكن فشل مع رمز المحارب
والشكوى هو أن الدعوة إلى القالب غامضة - لا تستطيع أن تقرر بين DOIT (M *) وDOIT (M CONST *)، على الرغم من أن في كل حالة، والمعلمة لا لبس فيه تكلف أو عدم CONST. بشكل مزعج، وإذا كنت توريد حجة قالب الثانية، قررت أنها لم تعد غامضة.
template< typename T1, typename T2 >
T1 const* doIt( T2 const* );
template< typename T1, typename T2 >
T1* doIt( T2* );
class M {};
class N : public M {};
void f()
{
M* m1 = NULL;
M const* m2 = NULL;
doIt<N>( m1 ); // Fail
doIt<N>( m2 ); // Fail
doIt<N,M>( m1 ); // OK
doIt<N,M>( m2 ); // OK
}
هل هذا مجرد خطأ مع المترجم رمز المحارب؟ (أو والخطأ مع دول مجلس التعاون الخليجي / مرئي C ++).
المحلول
ومن خطأ مع مترجم كود واريور.
وهذا ما يجب أن يحدث:
template< typename T1, typename T2 >
T1 const* doIt( T2 const* ); // 1
template< typename T1, typename T2 >
T1* doIt( T2* ); // 2
class M {};
class N : public M {};
void f()
{
M* m1 = 0;
M const* m2 = 0;
doIt<N>( m1 );
// In the above call - the compiler does the following (post argument deduction)
// 1) create a viable set of functions { N* doIt1<N,M>(const M*) , N* doIt2<N, M>(M*) }
// 2) check the conversion sequences - M* -> M* is better than M* -> const M*
// Since doIt2 has a "better" conversion sequence (hard to beat identity) it wins - no ambiguity
doIt<N>( m2 );
// 1) Viable functions: { doIt1<N,M>(const M*), doIt2<N,const M>(const M*) }
// 2) Conversion Sequence Ranking: both do identity - so both are good
// 3) Check to see if the "mother" template of either candidate is more specialized
// - Since doIt1 theoretically matches fewer types than doIt2, it is unambiguously more specialized (the standard specifies an algorithm to check this)
// - so doIt1 wins
}
وعلى أمل أن يساعد.
لا تنتمي إلى StackOverflow