Skip to content

Instantly share code, notes, and snippets.

@aceiii
Created February 5, 2016 13:27
Show Gist options
  • Save aceiii/5510337608a4a21caa5f to your computer and use it in GitHub Desktop.
Save aceiii/5510337608a4a21caa5f to your computer and use it in GitHub Desktop.
Possible implementation of stream serializer using templates and type traits to deal with classes and primitives
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <type_traits>
using namespace std;
/*
template <typename T>
class Serializer
{
public:
int operator() (typename enable_if<is_arithmetic<T>::value, T>::type ) {
cout << "serializer!" << endl;
return 1;
}
};
*/
/*
template <typename T>
class Serializer
{
public:
string operator() (const T& t) {
return t.serialize();
}
};
*/
class Stream
{
public:
Stream() {}
~Stream() {}
/*
template <typename T, typename S = Serializer<T>>
void write(const T& t) {
S s;
int result = s(t);
cout << "Serializing: " << result << endl;
}
*/
template <typename T>
void write(const typename enable_if<is_class<T>::value, T>::type& t) {
cout << "Serializing class -> " << t.serialize() << endl;
}
template <typename T>
void write(const typename enable_if<is_arithmetic<T>::value, T>::type& t) {
stringstream ss;
ss << t;
cout << "Serializing primitive -> " << ss.str() << endl;
}
};
class A
{
public:
string serialize() const {
return "A";
}
};
class B
{
public:
string serialize() const {
return "B";
}
};
class C
{
public:
string serialize() const {
return "C";
}
};
int main()
{
Stream s;
A a;
B b;
s.write<A>(a);
s.write<B>(b);
s.write<int>(1);
s.write<float>(34.99);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment