The mechanics of extension via free functions or member functions

后端 未结 5 937
挽巷
挽巷 2021-02-14 12:45

Loads of C++ libraries, the standard included, allow you to adapt your objects for use in the libraries. The choice is often between a member function or a free function in the

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-14 13:06

    The library doesn't do any of this at runtime, dispatch is done by the compiler when the calling code is compiled. Free functions in the same namespace as one of the arguments are found according to the rules of a mechanism called "Argument-Dependent Lookup" (ADL), sometimes called "Koenig lookup".

    In cases where you have the option either to implement a free function or a member function, it may be because the library provides a template for a free function that calls the member function. Then if your object provides a function of the same name by ADL, it will be a better match than instantiating the template, and hence will be chosen first. As Space_C0wb0y says, they might use SFINAE to detect the member function in the template, and do something different according to whether it exists or not.

    You can't change the behaviour of std::cout << x; by adding a member function to x, so I'm not quite sure what you mean there.

提交回复
热议问题