c++模板函数的重载
2020-01-16 本文已影响0人
help_youself
代码来自于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;
}