【问题标题】:Why is the code "foo::foo::foo::foob" compiling? [duplicate]为什么要编译代码“foo::foo::foo::foob”? [复制]
【发布时间】:2017-10-18 08:05:55
【问题描述】:

一位同事不小心写了这样的代码:

struct foo {
  foo() : baz(foobar) {}
  enum bar {foobar, fbar, foob};
  bar baz;
};

void f() {
  for( auto x : { foo::foobar,
                  foo::fbar,
                  foo::
                  foo::
                  foo::foob } );
    // ...
}

GCC 5.1.0 编译这个。

编译的规则是什么?

【问题讨论】:

  • 您能否更具体地说明您不希望编译干净的部分?
  • 它没有:godbolt.org/g/j2AbVn
  • 缺少包含文件,for 循环缺少语句,但除此之外它还能编译
  • 这个可以简化为struct foo { static const int v{42}; }; auto x{foo::foo::foo::foo::foo::v};
  • @sbi 哪一部分让你感到困惑?注入的类名?基于范围的 for 循环?

标签: c++ c++11 gcc language-lawyer names


【解决方案1】:

这里使用injected-class-name

在其自己的定义中,类的名称作为其自身的公共成员类型别名,用于lookup(除非用于命名constructor):这称为注入类名称

然后

foo::
foo::
foo::foob

foo::foo::foo::foobfoo::foob 相同。

然后for (auto x : {foo::foobar, foo::fbar, foo::foob }) 是一个range-based for loop (since C++11),它迭代由3 个枚举器组成的braced-init-list

【讨论】:

    【解决方案2】:

    我把这段代码改成了这样:

    #include <initializer_list>
    #include <iostream>
    struct foo {
      foo() : baz(foobar) {}
      enum bar {foobar, fbar, foob};
      bar baz;
    };
    
    int main() {
      for( auto x : { foo::foobar,
                      foo::fbar,
                      foo::
                      foo::
                      foo::foob } )
                      {
                          std::cout << "x=" << x << std::endl;
                      }
      return 0;
    }
    

    for 循环运行 3 次。输出为:“x=1 x=2 x=3”。


    foo::foo::foo::foobfoo::foob 相同。 所以

    for( auto x : { foo::foobar,
                      foo::fbar,
                      foo::
                      foo::
                      foo::foob } )
    

    是一样的

    for( auto x : { foo::foobar, foo::fbar, foo::foob } )
    {
    }
    

    表示x{ foo::foobar, foo::fbar, foo::foob }范围内

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2017-06-23
      • 2017-03-30
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多