stencet  v0.1.16
Build C++ web server modules that allow easy routing and deployment.
variant.h
1 /* Copyright (C) 2012-2013 Justin Berger
2  The full license is available in the LICENSE file at the root of this project and is also available at http://opensource.org/licenses/MIT. */
3 
4 #pragma once
5 #include "viewModel.h"
6 #include <memory>
7 #include <mxcomp/variant.h>
8 
9 namespace stencet {
10 
11  struct Variant;
12  using MapT = std::map<std::string, std::unique_ptr<Variant> >;
13  using ListT = std::vector< std::unique_ptr<Variant> >;
14  using VariantT = Variant_<MapT, ListT, std::string, double, int, bool>;
15 
16  struct Variant : public ViewModel, public VariantT {
17  public:
18  Variant();
19  template <typename T>
20  static Variant* Create(const T& t) {
21  auto rtn = new Variant();
22  *rtn = t;
23  rtn->managed = false;
24  return rtn;
25  }
26 
27  virtual Variant* at(const std::string& name);
28  virtual Variant* at(size_t);
29  Variant& operator[](const std::string& name);
30  Variant& operator[](size_t);
31 
32  template<typename T> Variant& append(const T&);
33 
34  virtual bool hasValue(const std::string& name);
35 
36  virtual Type getType() const;
37  virtual int asInt() const;
38  virtual void asString(std::string& str) const;
39  virtual size_t size() const override;
40 
41  template<typename T>
42  Variant& operator=(const std::initializer_list<T>&);
43  template<typename T>
44  Variant& operator=(const T&);
45  };
46 
47  template<typename T>
48  Variant& Variant::operator=(const std::initializer_list<T>& t){
49  ListT& list = this->as<ListT>();
50  list.resize(t.size());
51  for(size_t i = 0;i < t.size();i++)
52  list[i] = t.begin()[i];
53  return *this;
54  }
55 
56  template<typename T>
57  Variant& Variant::operator=(const T& t){
58  VariantT::operator =(t);
59  return *this;
60  }
61 
62  template<typename T> Variant& Variant::append(const T& t){
63  ListT& list = this->as<ListT>();
64  list.push_back( std::unique_ptr<Variant>( new Variant() ) );
65  *list.back() = t;
66  return *list.back().get();
67  }
68 }