Search code examples
c++templatesstructtraitstypename

C++: Construct strait with two same typenames from template


I'm fairly new to C++ and I'm trying my best to construct something like this:

enum class Unit { km, m, cm };


template<int v, Unit u>
struct Measure {
    static const int value = v;
    static const Unit unit = u;
};


template<typename Measure, typename Measure>
struct Measures_same {
    static const bool value(const Measure m1, const Measure m2) {
        return m1.unit == m2.unit;
    }
};

My goal here is that I can invoke my trait like this:

Measures_same<Measure<1, Unit::km>,Measure<1, Unit::cm>>::value

, which would return false. Obviously I am not allowed to define the same typename in the template twice (template), but I am unsure how else I should do it. If I remove one of them, the amount of arguments will not longer match.

How should I proceed?

Thanks in advance!


Solution

    1. Measure_same needs to use two different template parameters. If the types are the same, the return value of value will always be true. Use:

      template<typename Measure1, typename Measure2>
      struct Measures_same { ... };
      
    2. You don't need any inputs to Measure_same::value. Simply use:

      template<typename Measure1, typename Measure2>
      struct Measures_same {
          static const bool value() {
              return Measure1::unit == Measure2::unit;
          }
      };
      
    3. Use a function call to get the value from Measure_same. Use:

      Measures_same<Measure<1, Unit::km>,Measure<1, Unit::cm>>::value()
      

      For example:

      std::cout << std::boolalpha << Measures_same<Measure<1, Unit::km>,Measure<1, Unit::cm>>::value() << std::endl;