static if in plain c++?

后端 未结 4 1195
轻奢々
轻奢々 2021-02-13 20:13

Problem in short:
How could one implement static if functionality, proposed in c++11, in plain c++ ?

History and original prob

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 20:34

    Why not make the send implementation a policy of the sender class and use CRTP:

    template
    class SingleSenderPolicy
    {
        public:
        template< class memFunc >
        void callWrapperImpl(memFunc f, ...)
        {
            static_cast(this)->f(...);
        }
    };
    
    template< class Derived >
    class DoubleSenderPolicy
    {
        public:
        template< class memFunc >
        void callWrapperImpl(memFunc f, ...)
        {
            static_cast(this)->f(...);
            static_cast(this)->f(...);
         }
    };
    
    template< class SendPolicy>
    class Sender : public SendPolicy< Sender >
    {
    public:
        void sendMessage( ... )
        {
           // call the policy to do the sending, passing in a member function that
           // acutally performs the action
           callWrapperImpl( &Sender::sendMessageImpl, ... );
        }
    
        void doSomethingElse( ... )
        {
           callWrapperImpl( &Sender::doSomethingElseImpl, ... );
        }
    
    
    protected:
        void sendMessageImpl(... )
        {
            // Do the sending here
        } 
    
        void doSomethingElseImpl(... )
        {
            // Do the sending here
        } 
    };
    

    The public sendXXX functions in you class simply forward to the call wrapper, passing in a member function that implements the real functionality. This member function will be called according to the SendPolicy of the class. CRTP saves the use of bind to wrap the arguments and this pointer up with the member function to call.

    With one function it doesn't really cut down on the amount of code, but if you have a lot of calls it could help.

    Note: This code is a skeleton to provide a possible solution, it has not been compiled.

    Note: Sender and Sender are completely different types and do not share a dynamic inheritance relationship.

提交回复
热议问题