Why there is no concept of “const-correctness” for class's static member functions?

后端 未结 6 771
别那么骄傲
别那么骄傲 2020-12-19 01:13

Use case:

class A {
  static int s_common;
public:
  static int getCommon () const { s_common; };
};

Typically this results in an error as:

6条回答
  •  余生分开走
    2020-12-19 01:35

    A function that doesn't change any global state is pure. C++11 introduces attributes that might include [[pure]] on particular platforms.

    One problem with const is that it's part of the type of the function. Assigning that static const function to a "normal" function pointer would require a special conversion, cast, or decay rule. And as Luchian mentions, it would allow completely ambiguous overloading.

    Essentially you are describing forming a singleton object from the static members, sharing a common, qualified indirect access path. For the non-const object to appear const, it must be accessed through something, but there's no this. Would its decltype change? There is no good answer. If you want all this, then put them explicitly inside a class object.

提交回复
热议问题