gpt4 book ai didi

c++ - 重载函数以接受模板指针变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:02 25 4
gpt4 key购买 nike

在main函数中调用时使用push方法。然而,即使主函数中的参数是一个指针,它仍然使用函数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
}

最佳答案

您的问题与常量有关。

问题是,当您使用非常量对象指针调用 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 );
}

关于c++ - 重载函数以接受模板指针变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15755083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com