保罗万象的对象——Variant
对一个对象设置其可容纳的多种类型
通过类型对对象进行Set和Get,类型之间互不影响,一个类型只能又一个值
variant.h
/*
* variant.h
*
* Created on: 2012-3-9
* Author: vivence
*/
#ifndef VARIANT_H_
#define VARIANT_H_
namespace ghost{
template<typename... Tn>
class Variant;
template<>
class Variant<>{};
template<typename T, typename... Tn>
const T& GetVariant(const Variant<T, Tn...>& t);
template<typename T, typename... Tn>
T& GetVariant(Variant<T, Tn...>& t);
template<typename T, typename... Tn>
class Variant<T, Tn...> : public Variant<Tn...>{
T v_;
public:
const T& GetValue() const{return v_;}
T& GetValue(){return v_;}
template<typename TT>
const TT& Get() const{return GetVariant<TT>(*this);}
template<typename TT>
TT& Get(){return GetVariant<TT>(*this);}
template<typename TT>
void Set(const TT& t){Variant<Tn...>::Set(t);}
void Set(const T& t){v_ = t;}
};
template<typename T, typename... Tn>
const T& GetVariant(const Variant<T, Tn...>& t){return t.GetValue();}
template<typename T, typename... Tn>
T& GetVariant(Variant<T, Tn...>& t){return t.GetValue();}
} // namespace ghost
#endif /* VARIANT_H_ */
test.cpp
/*
* test.cpp
*
* Created on: 2012-3-9
* Author: vivence
*/
#include "variant.h"
#include <iostream>
#include <iomanip>
int main()
{
ghost::Variant<int, bool, char> test;
test.Set(1);
test.Set(false);
test.Set('a');
test.Set('b');
std::cout<<test.Get<int>()<<std::endl;
std::cout<<std::boolalpha<<test.Get<bool>()<<std::endl;
std::cout<<test.Get<char>()<<std::endl;
return 0;
}
By Evil.Ghost