【问题标题】:"binding reference of type discards qualifiers" when using [] operator使用 [] 运算符时的“类型的绑定引用丢弃限定符”
【发布时间】:2018-10-30 19:08:54
【问题描述】:

我在 C++ 应用程序中使用 C 样式的数组(需要与 C 代码交互),但是在数组上使用 [] 运算符时,我得到了“类型丢弃限定符的绑定引用”。这是一个小例子:

#include <iostream>
struct outer_struct {
  struct {
    int i;
  } array[1];
} temp_struct;

typedef decltype( static_cast<outer_struct*>(nullptr)->array[0]  ) typed;

void do_something_2(const typed &thing)
{
  std::cout << thing.i << std::endl;
}

void do_something_1(const outer_struct &thing)
{
  // error: binding reference of type ‘outer_struct::<unnamed struct>&’ to
  // ‘const outer_struct::<unnamed struct>’ discards qualifiers
  do_something_2(thing.array[0]);
}

int main()
{
  temp_struct.array[0].i = 2;
  do_something_1(temp_struct);
  return 0;
}

我原以为在 const 引用上使用 [] 运算符会返回一个 const 引用,但从编译器输出来看,情况似乎并非如此。将 do_something_1 的签名更改为

void do_something_1(outer_struct &thing)

解决了错误。我通常对 const 正确性没有任何问题,但老实说,我无法弄清楚我在这里做错了什么。任何帮助表示赞赏。

我正在使用 g++ 7.3.0。我也尝试过旧版本的 GCC。

【问题讨论】:

  • const T&amp; 其中TU&amp; 折叠为U&amp;,而不是const U&amp;。 (decltyle 导致引用类型)

标签: c++ arrays constants


【解决方案1】:

你需要删除 decltype 返回的额外引用(因为内置下标运算符的结果是一个引用):

using
inner_struct = ::std::remove_reference_t<decltype(::std::declval<outer_struct &>().array[0])>;

online compiler

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2015-11-29
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2014-02-07
    相关资源
    最近更新 更多