Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

c++ - Static member functions

After reading sbi and Eli Bendersky's answers in this question I started to wondering what static member functions are for.

A class' friend free function shouldn't be able to do anything a static member function can do? If so, why/when should I prefer a static member function to a friend free one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general:

Require access to private members

static member functions have access to private members of the class. If you need that, you can use a static member function. You have to declare it in the header anyway to give it access, so you may as well make it a member rather than a friend. It is commonly done this way for singletons that have a getInstance() method as singleton, and classes that use a static factory method createInstance() to ensure they are created on the heap. Both of these need access to the private constructor.

Meta-programming

static member functions are very good for template meta-programming where you can pass in a class and call its method without knowing at the point of call what function will actually get invoked. This is commonly called "compile-time polymorphism" and is an important part of meta-programming. std::char_traits is based on this principle.

Restricted access

The common use of a private static member function, just so that it can be accessed only by the class, and does not itself need access to private members, is not a good use of static member functions because it is part of the implementation detail of the class, and this is better done in the anonymous namespace of the compilation unit.

However if the static member function is protected it has use as it can get called by derived classes but not by external classes.

friend functions

  • Can have access to private members but need to be declared in the header anyway.
  • Can be used in meta-programming as part of an "overload" however still needs to be declared in the header. (Common example is operator<<)
  • Does not work for protected access with friendship as what you are trying to do here is restrict access to the method, not what the call has access to.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...