当我有这样的代码时:
输出结果为:
"void f(T&& arg): 可修改\n";
"void f(T&& arg): 可修改\n";
输出结果更加“直观”:
“在f(const MemoryBlock&)中。此版本不能修改参数。”;
“在f(MemoryBlock&&)中。此版本可以修改参数。”; 在我看来,仅通过将函数从模板更改为非模板就完全改变了rvalue引用的推断规则。 如果有人能向我解释一下,我会非常感激。
template<class T>
void f_(const T& arg)
{
cout << "void f(const T& arg): Cannot modify\n";
}
template<class T>
void f_(T&& arg)
{
cout << "void f(T&& arg): Can modify\n";
}
在主函数中我调用它:
int main()
{
MemoryBlock block;
f_(block);
f_(MemoryBlock());
return 0;
}
输出结果为:
"void f(T&& arg): 可修改\n";
"void f(T&& arg): 可修改\n";
但是当我将这段代码改为非通用代码时,也就是说,我不再使用函数模板,而是使用普通函数,
void f(const MemoryBlock&)
{
cout << "In f(const MemoryBlock&). This version cannot modify the parameter.\n";
}
void f(MemoryBlock&&)
{
cout << "In f(MemoryBlock&&). This version can modify the parameter.\n";
}
输出结果更加“直观”:
“在f(const MemoryBlock&)中。此版本不能修改参数。”;
“在f(MemoryBlock&&)中。此版本可以修改参数。”; 在我看来,仅通过将函数从模板更改为非模板就完全改变了rvalue引用的推断规则。 如果有人能向我解释一下,我会非常感激。
T
与MemoryBlock
的映射关系。 - Walter