为什么以下代码不能在 C++14 编译器中编译?如果我使用
const int i = 10;
int n = fun(i);
编译器报错。
但是,如果我使用
int n = fun(10);
而不是上面的语句,它工作正常。
示例:
template<typename T>
int fun(const T&&)
{
cout<<"fun"<<endl;
}
int main()
{
// int i = 10; // Not work
const int i = 10; // Not work
int n = fun(i);
// int n = fun(10); // Working fine
}
最佳答案
它失败了,因为添加 const 会阻止它成为转发引用。它成为对 const 右值的常规引用:
... A forwarding reference is an rvalue reference to a cv-unqualified template parameter that does not represent a template parameter of a class template (during class template argument deduction ([over.match.class.deduct])). ...
然后你传递给它一个左值。匹配失败。
关于c++ - C++ 中的模板引用参数推导失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460916/