C++ 模板特化右值
C++ template specialization rvalue
我正在学习 C++,但在模板专业化方面遇到了一些问题。我需要经常调用 Variable.Set() ,所以我让函数接受引用,这样它就不会花费很多时间来复制字符串。但是我遇到的问题是 Variable.Set<int>(5);
导致错误,因为参数是右值,我不知道解决方案。
error C2664: 'void Variable::Set(int &)': 无法将参数 1 从 'int' 转换为 'int &'
void main()
{
Variable var;
var.Set<int>(5);
}
struct Variable
{
int integer;
float floating;
std::string string;
template<typename T> void Set(T& v);
template<> void Set<int> (int& v) { integer = v; }
template<> void Set<float> (float& v) { floating = v; }
template<> void Set<std::string> (std::string& v) { string = v; }
};
您需要将参数更改为常量引用(如 Praetorian 评论中所述的 const&)
来自这个link:http://www.codesynthesis.com/~boris/blog/2012/07/24/const-rvalue-references/
while a const lvalue reference can bind to an rvalue, a const
rvalue reference cannot bind to an lvalue
我正在学习 C++,但在模板专业化方面遇到了一些问题。我需要经常调用 Variable.Set() ,所以我让函数接受引用,这样它就不会花费很多时间来复制字符串。但是我遇到的问题是 Variable.Set<int>(5);
导致错误,因为参数是右值,我不知道解决方案。
error C2664: 'void Variable::Set(int &)': 无法将参数 1 从 'int' 转换为 'int &'
void main()
{
Variable var;
var.Set<int>(5);
}
struct Variable
{
int integer;
float floating;
std::string string;
template<typename T> void Set(T& v);
template<> void Set<int> (int& v) { integer = v; }
template<> void Set<float> (float& v) { floating = v; }
template<> void Set<std::string> (std::string& v) { string = v; }
};
您需要将参数更改为常量引用(如 Praetorian 评论中所述的 const&)
来自这个link:http://www.codesynthesis.com/~boris/blog/2012/07/24/const-rvalue-references/
while a const lvalue reference can bind to an rvalue, a const rvalue reference cannot bind to an lvalue