Search code examples
c++c++11type-traits

Template Metaprogramming NamedPipe Client Server


I am writing a NamedPipe extraction for C++11 and would like to have the following API*:

template<typename Mode>
class NamedPipe final {
    public:
        void Open();

        std::enable_if<Mode == Receiver>
        void Send();

        std::enable_if<Mode == Receiver>
        void Receive();

        void Close();
}

So that use looks like so:

NamedPipe<Sender> pipe_sender("test");
NamedPipe<Reciever> pipe_receiver("test");
pipe_sender.Open();
pipe_receiver.Open();
pipe_sender.Send("Some data");
pipe_receiver.Receive();
pipe_sender.Receive(); <--- compilation error

I have been using the type_traits in C++11 but only really just got into them - I've really enjoyed using them but this is really flexing the learning curve. Is there anyone with enough knowledge to point me in the right direction?

* the first example is deliberately rough as I keep going around in circles with the template stuff - I really just need to be put on the right path!


Solution

  • You can force compilation errors easily with static assertions:

    template<typename Mode>
    class NamedPipe final {
        public:
            void Open();    
            void Send();    
            void Receive();    
            void Close();
    }        
    template<typename Mode>
    void NamedPipe<Mode>::Send() {
        static_assert(std::is_same<Mode, Sender>::value, "Cannot send from receivers");
        // blah blah implementation
    }        
    template<typename Mode>
    void NamedPipe<Mode>::Receive() {
        static_assert(std::is_same<Mode, Receiver>::value, "Cannot receive with senders");
        // blah blah implementation
    }
    

    This not only gives compilation errors, but it gives nice descriptive errors.