假设以下代码段:
template <class T>
void fct(T* a, T* b){
// do something
}
A a;
fct(&a, nullptr); // Problem here!
Run Code Online (Sandbox Code Playgroud)
这使得麻烦,因为调用参数的数据类型的A*,并nullptr_t因此编译器不能推断出模板参数T.
一般来说,我可以想象几个想法如何解决这个问题:
A* b = nullptr和使用fct(&a, b)fct为一个nullptr案例定义一个带有一个参数的重载fct(&a, static_cast<A*>(nullptr))或者是否有更清晰的解决方案,比如创建类似"typed nullptr"的东西?
这显示了它的要点:
#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;
}
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法使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 …Run Code Online (Sandbox Code Playgroud)