Advertisement
GeneralGDA

C++11 style Variant

Feb 25th, 2015
552
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. class MorphingParameter final
  2. {
  3. public:
  4.  
  5.     MorphingParameter(const MorphingParameter&) = default;
  6.     MorphingParameter& operator=(const MorphingParameter&) = delete;
  7.     MorphingParameter() = delete;
  8.  
  9.     static MorphingParameter from_float(float value);
  10.     static MorphingParameter from_int32(std::int32_t value);
  11.  
  12.     float get_float_value() const;
  13.     std::int32_t get_int32_value() const;
  14.  
  15. private:
  16.  
  17.     enum class ParameterType
  18.     {
  19.         Float,
  20.         Int32,
  21.     };
  22.  
  23.     union Storage final
  24.     {
  25.         Storage& operator=(const Storage&) = delete;
  26.  
  27.         explicit Storage(float value);
  28.         explicit Storage(std::int32_t value);
  29.  
  30.         const float float_value;
  31.         const std::int32_t int32_value;
  32.     };
  33.  
  34.     explicit MorphingParameter(float value);
  35.     explicit MorphingParameter(std::int32_t value);
  36.  
  37.     const ParameterType type_;
  38.     const Storage value_;
  39. };
  40.  
  41. MorphingParameter MorphingParameter::from_float(const float value)
  42. {
  43.     return MorphingParameter { value };
  44. }
  45.  
  46. MorphingParameter MorphingParameter::from_int32(const std::int32_t value)
  47. {
  48.     return MorphingParameter { value };
  49. }
  50.  
  51. MorphingParameter::MorphingParameter(const float value)
  52.     : type_(ParameterType::Float)
  53.     , value_(value)
  54.  
  55. {
  56. }
  57.  
  58. MorphingParameter::MorphingParameter(const std::int32_t value)
  59.     : type_(ParameterType::Float)
  60.     , value_(value)
  61.  
  62. {
  63. }
  64.  
  65. MorphingParameter::Storage::Storage(const float value)
  66.     : float_value(value)
  67.  
  68. {
  69. }
  70.  
  71. MorphingParameter::Storage::Storage(const std::int32_t value)
  72.     : int32_value(value)
  73.  
  74. {
  75. }
  76.  
  77. float MorphingParameter::get_float_value() const
  78. {
  79.     assert(type_ == ParameterType::Float);
  80.     return value_.float_value;
  81. }
  82.  
  83. std::int32_t MorphingParameter::get_int32_value() const
  84. {
  85.     assert(type_ == ParameterType::Int32);
  86.     return value_.int32_value;
  87. }
  88.  
  89. int _tmain(int, _TCHAR*)
  90. {  
  91.     std::vector<MorphingParameter> parameters;
  92.     parameters.push_back(MorphingParameter::from_float(1.0f));
  93.  
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement