1

I am using Visual Studio versions 2005 and 2012 for this, the code below compiles and there are no issues in vs2005, but it generates an error in vs2012. I have distilled the code I was working on down to the sample below which compiles and runs (in vs2005)

#include <map> 

//Arbitrary class
class SimpleClass
{
private:
     int member;

public:
     explicit SimpleClass( int i ) : member(i) {}
     operator int() const { return member;} 
};

//In code I have a map with these types and make_pair is invoked
//when an insert occurs into that map
typedef std::pair<SimpleClass,SimpleClass> SCPair;

//simple fn to replace myMap.insert(...)
void lvalref_test( const SCPair& sp )
{
    return;
}

int main( unsigned int argc, const char** argv ) 
{
     const int anInt = 2;
     //make_pair creates a pair<SimpleClass,SimpleClass> from
     //the instance of pair<int,SimpleClass> in the normal way
     //and Because SimpleClass is constructable from an int, 
     //the creation succeeds (In vs2005)
     lvalref_test( std::make_pair( anInt, SimpleClass(1) ) );
     return 0;
}

vs2012 gives me:

error C2664: 'lvalref_test' : cannot convert parameter 1 from 'std::pair<_Ty1,_Ty2>' to 'const SCPair &'

I've looked at the difference between the std::pair implementations in both

vs2005

template<class _Other1,
    class _Other2>
    pair(const pair<_Other1, _Other2>& _Right)
    : first(_Right.first), second(_Right.second)
    {   // construct from compatible pair
    }

vs2012

template<class _Other1,
    class _Other2>
    pair(const pair<_Other1, _Other2>& _Right,
        typename enable_if<is_convertible<const _Other1&, _Ty1>::value
            && is_convertible<const _Other2&, _Ty2>::value,
            void>::type ** = 0)
    : first(_Right.first), second(_Right.second)
    {   // construct from compatible pair
    }

I guess that the enable_if is causing the behaviour change, but I am not quite sure why.

I know how to fix the error I see, I can pass through an instance of SimpleClass and all is fine and dandy. My Question here is should this still deduce the correct template parameters and create the right pair type? Has this behaviour changed or have I made a mistake somewhere?

The answer is yes I made a mistake - I ignored the obvious explicit keyword throughout and dived headlong into the mechanism....

4

1 回答 1

3

它不应该编译。您的构造函数需要显式构造,但通过尝试隐式转换该对,您正在尝试执行隐式转换。严格来说,这不应该编译。

VS2005 的行为是有缺陷的——无论是因为标准缺陷还是因为它们有缺陷。VS2012 中的行为是正确的。

于 2012-10-31T13:43:49.377 回答