May 30, 2018

[C++][Language][Design] function as first class citizen in C++

Reference:
https://yinwang0.wordpress.com/2013/12/24/oop/
Prof. Peter Norvig on design pattern [1998]

https://github.com/boostcon/cppnow_presentations_2015/blob/master/files/functions_want_to_be_free.pdf



  • Focus on the goal, not the syntax
    • maximize encapsulation
    • Not to write member functions
    • Note: Or, if it's pure, consider writing it as callable object, which introduce a layer of 'namespace' and take advantage of EBO(Empty base class optimizations), [no_unique_address], refer to: [C++][accu2018] Tricks library implementation to know), i.e no constructor call overhead, class as a layer of namespace.
  • Prefer non-friend free functions
    • Isolates changes in implementation
    • Forces implementation via the public interface
  • Write them as algorithm instead member function.

How?
  • Implement functions in terms of other functions
  • Everything left over cannot be a normal function

Header:
<utility>

Keep using std::move_if_noexcept in mind.

With testing equivalence (keep Regular type in mind):
  • operator==(lhs, rhs)
  • operator<(lhs, rhs)
  • use above 2 to do the rest of test.

Swap:
  • Member swap should be deprecated
  • Free function swap should rarely be specialized
  • std::exchange
template<typename T>
void swap(T & lhs, T & rhs) {
rhs = std::exchange(lhs, std::move(rhs));
}


Erase:


repeat_n:
  • Range library.

operators that must be members:
  • operator=
  • operator[]
  • operator()
  • operator->

Sum up:
  • If it must be a member, make it a member
    • Virtual functions
    • Member operators
    • Constructors
  • If it can be a non-friend function, make it free
    • Only if no loss of efficiency
      • Remember insert (carefully designed)
  • Otherwise, maximize consistency

ISO Reference:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.