Kin*_*lin 5 c++ templates pointers overloading
在main函数中调用时会用到push方法。但是,即使 main 函数中的参数是指针,它仍然使用该函数void Push(const DATA_TYPE& newValue)
。
难道它不应该使用另一个,因为那是接受指针的那个吗?如果存在指针变量,如何更改第二个函数中的参数以覆盖第一个函数?
template<typename DATA_TYPE>
void Push(const DATA_TYPE& newValue)
{
//do stuff
}
template<typename DATA_TYPE>
void Push(const DATA_TYPE *newValue)
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
你的问题在于常量。
问题是,当您使用Push(p)
非常量对象指针调用时,P * p
第一个版本在设置 DATA_TYPE= 时完全有效P*
,给出了 的函数签名Push( const P* & )
。相比之下,带有 DATA_TYPE= 的第二个版本需要在类型签名中P
添加 来获取。这意味着选择第一个版本而不是第二个版本,因为它是完全匹配的。const
Push( const P* )
下面是一个例子来说明发生了什么:
这是一个例子:
#include <iostream>
class Foo
{
public:
template<typename DT>
void Push(const DT& newValue)
{
std::cout<<"In const DT& version"<<std::endl;
}
template<typename DT>
void Push(const DT *newValue)
{
std::cout<<"In const DT* version"<<std::endl;
}
};
int main()
{
Foo f;
int i=7;
// Since i is not const we pickup the wrong version
f.Push( i ); // const DT& ( DT = int )
f.Push( &i ); // const DT& ( DT = int* )
// Here's using a const pointer to show it does the right things
const int * const_i_ptr = &i;
f.Push( const_i_ptr ); // const DT* ( DT = int );
// Now using a const object everything behaves as expected
const int i_const = 7;
f.Push( i_const ); // const DT& ( DT = int );
f.Push( &i_const ); // const DT* (DT = int );
}
Run Code Online (Sandbox Code Playgroud)