STD ::对行为的对模板类型扣除?(否,显式关键字错误)

Template Type deduction of std::pair change in behavior? (no, explicit keyword error)

本文关键字:关键字 错误 STD 类型      更新时间:2023-10-16

我正在使用Visual Studio版本2005和2012为此,下面的代码编译了,并且VS2005中没有任何问题,但在VS2012中会产生错误。我已经将我正在处理的代码蒸馏到下面的样本,该样本是编译和运行的(在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给我:

错误c2664:'lvalref_test':无法从中转换参数1 'std :: pair&lt; _ty1,_ty2>'to'const scpair&amp;'

我已经查看了两个

中的std ::配对实现之间的区别

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
    }

我猜enable_if正在导致行为发生变化,但我不太确定为什么。

我知道如何修复我看到的错误,我可以通过简单的实例,一切都很好。我在这里的问题是否应该推断出正确的模板参数并创建合适的对类型?这种行为改变了还是我在某个地方犯了一个错误?

答案是是的,我犯了一个错误 - 我忽略了整个过程中明显的explicit关键字,并直接跳入机制....

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

vs2005的行为是不足的 - 是因为标准缺陷还是由于它们有缺陷。VS2012中的行为是正确的。