Effective C + + clause 35 Consider alternatives other than the virtual function

Source: Internet
Author: User

1. In an inheritance hierarchy, different classes to implement different implementations of the same interface, the first thought might be virtual function, assuming that there is an inheritance system, each layer in the integration system needs a called fun function, then it might be implemented like this:

clase base{public    : ...     Virtual Fun (int  num) {...} Private :    ...} class Derived: public base{public:    ...     Virtual Fun (int  num) {}private:    ...}
View Code

But there are other options besides setting the fun as a virtual function.

2. "The template method mode is realized by Non-virtual interface technique"

The basic idea of this method is to "make the client call the private virtual function indirectly through the public non-virtual member function, become Non-virtual interface (NVI) technique", it is the so-called template A unique representation of the method design pattern (not related to template). That is:

classbase{ Public:    ...    voidWrapperintnum) {    ...   //do some work beforehandFun (num); ...   //do some post-mortem work    }Private:    Virtual voidFunintnum) {...}};classDerived: Publicbase{ Public:    ...Private:    Virtual voidFunintnum) {...}};
View Code

The advantage of calling virtual functions indirectly through the wrapper function is that the Wraper function can do some preparatory work before the virtual function fun is called and do some post-mortem work after the fun is called (as noted)

However, the code above sets the fun to private, so it cancels the possibility of derived inheriting base, so you can set the fun to protected (if you set it to public it will not implement the NVi method)

3. "By function pointers is absorbing strategy mode"

The NVI technique only modifies the virtual function, adds a layer of wrapper function, and another alternative is to add a function pointer to each class in the inheritance hierarchy, pointing to the desired function, namely:

class base{public:    void (*PTRF) (int);    ...    Base (PTRF para):p TR (para) {...} Private :    PTRF ptr;} class Derived: public base{public    ...    Derived (PTRF para):p (para) {...} Private :    ...}
View Code

This provides greater flexibility: different entities of the same type can invoke different functions, and functions that can be called by the same entity can be changed at run time.

The disadvantage is that the function that P points to is no longer a member function, and if you want to access the non-public part of the class you can only weaken the encapsulation of the class: Set the function to friend or use the Non-public class member to public or provide the public interface to get Non-public members.

4. "Complete strategy mode with Tr1::function"

The 3 policy provides some flexibility, but not necessarily with pointers, using the function class template in <functional> for greater flexibility (the function template is described in clause 54), namely:

base{public:    function<void(int) > ptr;    ... Private :    ...} Derived: public base{public:    ... Private :    ...}
View Code

The advantage of this strategy compared to 3 is that PTR "can hold any callable object (callable entity, function pointer, function object, or member function pointer) as long as its signature is compatible with the demand side", thus providing a greater elasticity than 3. The PTR method is like this:

void Fun (int  num) {...} PTR=&fun;

As stated above, PTR can point to a non-member function, a static member function, or to a function object, or it can be assigned a value using a function pointer, but it also requires additional action to point to the member function because the member function has the default this pointer as the first argument, Using the BIND function template in the same file can solve this problem, the BIND function template returns a function pointer, and the BIND function template prototype looks like this:

Template <classclass... Args>bind (Fn&& fn,args&& .... Args);

The first parameter is the function pointer, the next argument is the parameter required by the function, if the argument is a definite value, then the parameter of the function pointer returned by BIND is set to that value, and if the parameter is to be preserved, the placeholder TR1::p laceholders::_1,tr1:: placeholders::_2. TR1::p laceholders::_n, i.e.:

class demo{public:    int fun (int) {...}    ... Private :    ...}
View Code
Demo tmp;ptr=bind (&demo::fun,tmp,tr1::p laceholders::_1);
View Code

This binds the PTR to the member function.

For the specific use of function class templates and bind functions templates, see:

http://blog.csdn.net/xiucaijiang/article/details/5999441

Http://www.cplusplus.com/reference/functional/bind/?kw=bind

5. "Classical Strategy Mode"

Traditional strategy practice will make fun into a separate virtual function in the inheritance system, namely:

class fun{public:    virtualvoid fun (int  num) {...}    ... Private :    ...} class base{public:    Base (fun *para):p TR (para) {...    } void Fun () {ptr-> fun();}    ... Private :    fun * ptr;    ...}
View Code

The advantage of this strategy is that it provides the possibility of incorporating an existing fun function into use, as long as a new derived class is added to the Fun class integration System.

Effective C + + clause 35 Consider alternatives other than the virtual function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.