c++ - C++ 中的模板引用参数推导失败

标签 c++ templates constants c++14

为什么以下代码不能在 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 右值的常规引用:

[temp.deduct.call/3]

... 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/

相关文章:

C++模板语法

php - 我可以在 PHP 类上定义 CONST 吗?

c++ - Pugixml - 解析具有前缀映射和不带前缀映射的命名空间

c++ - 管道到 C++ 流

c++ - 模板类 C++/Qt

c - 在头文件中声明全局变量 `extern const int` 但在源文件中仅声明 `int`

c++ - 为什么将 "pointer to pointer to non-const"转换为 "pointer to pointer to const"是不合法的

c++ - 安装时如何使NodeJS软件包生成C++/WebAssembly?

c++ - XCode:多维数组的堆栈大小限制

c++ - 避免使用 C++ 中的默认模板类/结构 <>