如何将NULL指定为模板函数的指针类型参数

时间:2011-01-04 17:23:51

标签: c++

这显示了它的要点:

#include <utility>

class A {
public:
    A() { }
};

class B {
public:
    B() { }
};

typedef std::pair<A*, B*> ABPair;

int main(int argc, char* argv[])
{
    B* b = 0;               // no C2440
    ABPair p2(new A(), b);

    ABPair p1(new A(), 0);  // C2440

    return 0;
}

是否有更好的方法使p1声明工作而不仅仅是强制转换,例如 ABPair p1(new A(), (B*)NULL)?这似乎很常见&amp;这将是一种“正确”的方式来做到这一点..并且铸造它不是正确的方式。

在VS 2010上,这是完整的错误:

1>ClCompile:
1>  test.cpp
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(163): error C2440: 'initializing' : cannot convert from 'int' to 'B *'
1>          Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(247) : see reference to function template instantiation 'std::_Pair_base<_Ty1,_Ty2>::_Pair_base<_Ty,int>(_Other1 &&,_Other2 &&)' being compiled
1>          with
1>          [
1>              _Ty1=A *,
1>              _Ty2=B *,
1>              _Ty=A *,
1>              _Other1=A *,
1>              _Other2=int
1>          ]
1>          c:\users\charliearnold\documents\visual studio 2010\projects\test\test\test.cpp(20) : see reference to function template instantiation 'std::pair<_Ty1,_Ty2>::pair<A*,int>(_Other1 &&,_Other2 &&)' being compiled
1>          with
1>          [
1>              _Ty1=A *,
1>              _Ty2=B *,
1>              _Other1=A *,
1>              _Other2=int
1>          ]
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(163): error C2439: 'std::_Pair_base<_Ty1,_Ty2>::second' : member could not be initialized
1>          with
1>          [
1>              _Ty1=A *,
1>              _Ty2=B *
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(167) : see declaration of 'std::_Pair_base<_Ty1,_Ty2>::second'
1>          with
1>          [
1>              _Ty1=A *,
1>              _Ty2=B *
1>          ]
1>
1>Build FAILED.

2 个答案:

答案 0 :(得分:11)

不是真的。 nullptr将在C ++ 0x中解决此问题,但现在请写(B*)0

答案 1 :(得分:5)

您可以使用“make_xxx()”模式:

#include <utility>

class A {
public:
    A() { }
};

class B {
public:
    B() { }
};

typedef std::pair<A*, B*> ABPair;

ABPair make_ABPair(A* pa, B* pb) 
{
    return ABPair(pa, pb);
}


int main(int argc, char* argv[])
{
    B* b = 0;               // no C2440
    ABPair p2(new A(), b);

    //ABPair p1(new A(), 0);  // C2440
    ABPair p1(make_ABPair(new A(), 0));

    return 0;
}

这样,您不仅可以传递0,还可以传递任何可隐式转换为A*B*的内容。