Calling a static method by repeating the object name?

后端 未结 3 1393
-上瘾入骨i
-上瘾入骨i 2020-12-15 15:14

I have a singleton:

struct foo {
  static foo& instance() {
    static foo f;
    return f;
  }
};

When re-arranging some code I ended

3条回答
  •  旧巷少年郎
    2020-12-15 15:39

    Because of [class]/2:

    A class-name is inserted into the scope in which it is declared immediately after the class-name is seen. The class-name is also inserted into the scope of the class itself; this is known as the injected-class-name.

    So foo::foo is an injected class name, denoting foo itself.


    Actually it's a bit more complicated: according to [class.qual]/2, foo::foo alone denotes a constructor of foo. In order to denote a class, it should either be preceded by struct (making it elaborated-type-specifier), or followed by :: (making it a nested-name-specifier - this is your case), or be a base-specifier (for example struct bar : foo::foo {};).

提交回复
热议问题