美文网首页
c++模板函数的重载

c++模板函数的重载

作者: help_youself | 来源:发表于2020-01-16 20:49 被阅读0次

     代码来自于facebook的folly库。
    cursor.h

    #pragma once
    #include <iostream>
    namespace zsy{
    template <class Derived>
    class Writable{
    public:
      template <class T>
      typename std::enable_if<std::is_arithmetic<T>::value>::type write(T value) {
        const uint8_t* u8 = reinterpret_cast<const uint8_t*>(&value);
        Derived* d = static_cast<Derived*>(this);
        d->push(u8, sizeof(T));
      }
      template <class T>
      void writeLE(T value) {
        Derived* d = static_cast<Derived*>(this);
        d->write(value);
      }
      void push(const uint8_t* buf, size_t len) {
        Derived* d = static_cast<Derived*>(this);
        if (d->pushAtMost(buf, len) != len) {
        }
      }
    };
    class RWCursor:public Writable<RWCursor>{
    public:
        size_t pushAtMost(const uint8_t* buf, size_t len){
            std::cout<<__FUNCTION__<<std::endl;
            return len;
        }
    };
    class QueueAppender:public Writable<QueueAppender>{
    public:
      template <class T>
      typename std::enable_if<std::is_arithmetic<T>::value>::type write(T value){
        std::cout<<"queue "<<__FUNCTION__<<value<<std::endl;
      }
        size_t pushAtMost(const uint8_t* buf, size_t len){
            std::cout<<"queue "<<__FUNCTION__<<std::endl;
            return len;
        }
    };
    }
    

    test.cc

    #include <iostream>
    #include "cursor.h"
    int main(){
        zsy::RWCursor rw;
        uint32_t len=32;
        rw.writeLE(len);
        zsy::QueueAppender appender;
        appender.writeLE(len+1);
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:c++模板函数的重载

          本文链接:https://www.haomeiwen.com/subject/dcdqzctx.html