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

标签 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)?这似乎很常见,并且会有一种“正确”的方法来做到这一点......并且转换它不是正确的方法。

在 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.

最佳答案

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

关于c++ - 如何将 NULL 指定为模板函数的指针类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4596499/

相关文章:

c++ - "this"是否也适配函数指针?

c++ - 我应该如何从 Eigen 3中的张量切片中获取 vector ?

c++ - 使用 OpenCV CascadeClassifier : . exe 的人脸检测已触发断点

c++ - lua的表模拟

c++ - 无法识别的命令行选项 “-std=c++11”

c++ - string_view 真的会导致释放后使用错误吗?

c++ - 未调用 move 赋值运算符

c++ - 移动或倍增是否更快,为什么?

c++ - Qt Designer - 如何将信号连接到静态函数?

c++ - 你能使 Visual Studio 12 输出 .o 文件而不是 .obj 吗?