fork download
  1. #include <string>
  2. #include <map>
  3. #include <memory>
  4. #include <vector>
  5. #include <iostream>
  6.  
  7. struct Parameter
  8. {
  9. };
  10.  
  11. template<typename T>
  12. struct TypedParameter : public Parameter
  13. {
  14. TypedParameter (const T& data): data(data){};
  15. T data;
  16. };
  17.  
  18. struct ParameterList
  19. {
  20. template <class... NamedParams>
  21. ParameterList(NamedParams... namedParams)
  22. {
  23. buildList(namedParams...);
  24. }
  25.  
  26. std::map<std::wstring, std::shared_ptr<Parameter>> list;
  27.  
  28. template<class T> void addParameter(const std::wstring& name, const T& param)
  29. {
  30. list[name] = std::shared_ptr<Parameter>(new TypedParameter<T>(param));
  31. }
  32.  
  33. template<class T> T& getParameter(const std::wstring& name) const
  34. {
  35. return static_cast<TypedParameter<T>*>(list.at(name).get())->data;
  36. }
  37. private:
  38. template <class... NamedParams>
  39. void buildList() {}
  40. template <class Name, class Value, class... NamedParams>
  41. void buildList(Name&& name, Value&& value, NamedParams... restParams)
  42. {
  43. addParameter(name, value);
  44. buildList(restParams...);
  45. }
  46. template<class Single, class... Rest>
  47. void buildList(const Single&, Rest... rest);
  48. };
  49.  
  50. class Test
  51. {
  52. private:
  53. const ParameterList _param;
  54. protected:
  55. public:
  56. Test(ParameterList p):
  57. _param(p)
  58. {
  59. }
  60.  
  61. Test(const std::wstring& name, int age) : _param(L"name", name, L"age", age)
  62. {
  63. }
  64.  
  65. void Present()
  66. {
  67. std::wcout << L"My name is " << _param.getParameter<std::wstring>(L"name");
  68. std::wcout << L" and I'm " << _param.getParameter<int>(L"age") << L" years old." << std::endl;
  69. }
  70. };
  71.  
  72. int main() {
  73. Test test(L"Piotr", 42);
  74. test.Present();
  75. }
Success #stdin #stdout 0s 3040KB
stdin
Standard input is empty
stdout
My name is Piotr and I'm 42 years old.