c++ - 模板元编程 NamedPipe 客户端服务器

标签 c++ c++11 typetraits

我正在为 C++11 编写 NamedPipe 提取,并希望拥有以下 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();
}

所以使用看起来像这样:

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

我一直在使用 C++11 中的 type_traits,但只是真正开始使用它们——我真的很喜欢使用它们,但这确实在弯曲学习曲线。有没有人有足够的知识为我指明正确的方向?

* 第一个例子是故意粗略的,因为我一直在绕着模板的东西转圈——我真的只需要走上正确的道路!

最佳答案

您可以使用静态断言轻松强制编译错误:

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
}

这不仅会产生编译错误,还会产生很好的描述性错误。

关于c++ - 模板元编程 NamedPipe 客户端服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12252094/

相关文章:

c++ - 一次通过 O(n) 时间从大量 URL 列表中查找唯一的 URL

c++ - DirectX 9.0(世界坐标移动我的对象(三角形)动画

c++ - gcc 4.6 和 4.7 之间的默认构造函数差异

c++ - 找不到用户定义的整数文字

c++ - std::integral_constant<bool> 的否定

c++ - std::is_same_v与非专业模板

c++ - 是基类型的有符号/无符号部分还是限定符

c++ - 编辑框闪烁

c++ - 在没有 malloc 和 free 的情况下存储和回收堆分配的可变大小对象

c++ - BOOST_PHOENIX_ADAPT_FUNCTION(...) 在模板化容器上使用模板化函数