【问题标题】:why const before template parameter does not work为什么模板参数之前的 const 不起作用
【发布时间】:2021-08-16 13:03:08
【问题描述】:

我很困惑为什么下面的代码不起作用?

编译器说: 错误:无法将“int&”类型的非常量左值引用绑定到“int”类型的右值 6 |常量 T a = 1;

template<typename T>
void f(T&& t)
{
    const T a = 1;
}

int main()
{
    int i;
    int& k = i;
    f(k);
}

【问题讨论】:

  • const typename std::remove_reference&lt;decltype(t)&gt;::type&amp; a = 1;

标签: c++ templates


【解决方案1】:

使用f(k); 我们调用template&lt;typename T&gt; void f(T&amp;&amp; t)T = int&amp;

const T 不是const int&amp;(也不是int const&amp;)而是int&amp;(因为const 应用于引用是无用的)。

int&amp; a = 1; 无效。

【讨论】:

  • 为什么(因为 const 应用于引用是无用的)?那是不是 T& 不是类型所以我们不能添加 const?
  • @Baker-xie “对 const int 的引用”是有道理的,但“对 int 的 const 引用”没有意义,因为引用本身永远无法修改,只能修改它所引用的内容。跨度>
【解决方案2】:

要添加到其他响应,您可以很容易地看到,如果您使用的是东部 const 样式:

template<typename T>
void f(T&& t)
{
    T const a = 1;
}

现在,编译器将实例化为如下所示:

template<>
void f(int& t) {
    int& const a = 1;
}

const 关键字总是适用于它左边的东西,除非没有。

它适用于整个引用,但在 C++ 中不能更改引用,所以它不会改变任何东西!

所以这几乎等同于:

template<>
void f(int& t) {
    int& a = 1;
}

正如其他答案所说,无效。

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多