template return value error C2440: “初始化”: 无法从“const T”转换为“const Player *&”
模板返回值参数,和const T&, T const&问题。
1.我有如下模板,当类型为不带*参数的时,一切正常
template<typename T>
const T & Get(const T & aa)
{
const T & b = aa;
std::cout << b << std::endl;
return b;
}
int main(int, char **)
{
int a = 10;
const int& b = Get<int>(a);
}
2. 当使用带*指针类型的话,报错
error C2440: “初始化”: 无法从“const T”转换为“const Player *&”
[build] with
[build] [
[build] T=Player *
[build] ]
看代码21行,用Player* const& 接就可以正常编译通过,因为T是Player*, 所以引用类型是 Player* const& 不让改指向,const Player* & 可以改指向, 但是不能改值。
template<typename T>
const T & Get(const T & aa)
{
const T & b = aa;
std::cout << b << std::endl;
return b;
}
class Player
{
public:
void func()
{
Player* pp = new Player();
std::cout << pp << std::endl;
// Player* const& cc = Get<Player*>(pp); // 这个为正常的情况
const Player* & cc = Get<Player*>(pp);// 这个编译报错。
std::cout << pp << std::endl;
}
int a = 10;
};
int main(int, char **)
{
int a = 10;
const int& b = Get<int>(a);
Player cc;
cc.func();
}

浙公网安备 33010602011771号