// Package.h
#pragma once
#include <boost/any.hpp>
#include <array>
#include <list>
#include <string>
typedef struct
{
int command;
}Header, *PHeader;
class Package
{
public:
Package(Header header) : header_(header)
{
}
friend Package& operator<<(Package& pg, int i);
friend Package& operator<<(Package& pg, const std::string& str);
template<typename T, size_t N>
friend Package& operator<<(Package& pg, std::tr1::array<T, N> const arr)
{
pg.body_.push_back(arr);
return pg;
}
friend Package& operator>>(Package& pg, int &i);
friend Package& operator>>(Package& pg, std::string& str);
template<typename T, size_t N>
friend Package& operator>>(Package& pg, std::tr1::array<T, N> &arr)
{
arr = boost::any_cast<std::tr1::array<T, N> >(pg.body_.front());
pg.body_.pop_front();
return pg;
}
private:
Header header_;
std::list<boost::any> body_;
};
// Package.cpp
#include "stdafx.h"
#include "Package.h"
Package& operator<<(Package& pg, int i)
{
pg.body_.push_back(i);
return pg;
}
Package& operator<<(Package& pg, const std::string& str)
{
pg.body_.push_back(str);
return pg;
}
Package& operator>>(Package& pg, int &i)
{
i = boost::any_cast<int>(pg.body_.front());
pg.body_.pop_front();
return pg;
}
Package& operator>>(Package& pg, std::string& str)
{
str = boost::any_cast<std::string>(pg.body_.front());
pg.body_.pop_front();
return pg;
}
// main.cpp
#include "stdafx.h"
#include "Package.h"
#include <iostream>
#include <array>
int _tmain(int argc, _TCHAR* argv[])
{
Header header;
header.command = 100;
Package pg(header);
int x = 123;
std::string str("abc");
std::tr1::array<int, 3> arr = {4, 5, 6};
pg << x << str << arr;
int x2;
std::string str2;
std::tr1::array<int, 3> arr2;
pg >> x2 >> str2 >> arr2;
std::cout << x2 << std::endl;
std::cout << str2 << std::endl;
for (int i=0; i<arr2.size(); ++i)
{
std::cout << arr2[i];
}
system("pause");
return 0;
}