【发布时间】:2018-12-24 23:33:36
【问题描述】:
请求一些帮助以了解右值引用的类型推导。非模板版本失败并出现以下错误,我理解原因。
错误:无法绑定“const char*&”类型的非常量左值引用 到 'const char*' 类型的右值
在 C++11 中,如果我将函数 void Firstfun(const Key& key) 更改为 void Firstfun(const Key&& key),那么它会编译,但是模板版本可以与左值引用参数一起正常工作。
至于模板化版本,我认为编译器必须生成带有右值引用的函数,因此使用__PRETTY_FUNCTION__ 对其进行了检查,但在 PRETTY_FUNCTION 的输出中没有看到它。
我确实遇到过this 讨论,其中@Anirban 提到了这些内容。
对于 wrapper(A());,类型参数 T 仍将推导出为 A, 参数 u 的类型为 A&&,称为右值引用 到A。
以下是我的问题:
- 编译器如何处理模板化版本以使其接受右值?
- 针对非模板版本的修复
void Firstfun(const Key&& key),是否有效且可接受?
非模板版本
#include <iostream>
namespace somens {
class Firstclass {
public:
void Firstfun(const char*& key) {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};
class Secondclass {
Firstclass f_class;
char* create_buf(){
char * buf = new char[10]; //buf will be freed elsewhere.
return buf;
}
public:
void Secondfun (){
f_class.Firstfun(create_buf());
}
};
}
int main () {
somens::Secondclass s_class;
s_class.Secondfun();
}
非模板版本的输出
错误:无法绑定“const char*&”类型的非常量左值引用 到 'const char*' 类型的右值
模板版
#include <iostream>
namespace somens {
template<typename Key>
class Firstclass {
public:
void Firstfun(const Key& key) {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};
class Secondclass {
Firstclass<const char*> f_class;
char* create_buf(){
char * buf = new char[10]; //buf will be freed elsewhere.
return buf;
}
public:
void Secondfun (){
f_class.Firstfun(create_buf());
}
};
}
int main () {
somens::Secondclass s_class;
s_class.Secondfun();
}
模板化版本的输出
void somens::Firstclass::Firstfun(const Key&) [with Key = const 字符*]
【问题讨论】:
标签: c++ c++11 templates rvalue-reference