How to define operator overload without member for class template?

I have a class template that has a constructor that takes std :: chrono :: duration, because I want to be able to use chrono_literals to create it. Now I am trying to determine the overload of a statement other than a member, but I cannot get it to work with a duration constructor:

#include <chrono>
#include <iostream>

using namespace std;

template <int n> struct MyClass {
  MyClass() = default;

  template <typename REP, typename PERIOD>
  constexpr MyClass(const std::chrono::duration<REP, PERIOD> &d) noexcept
      : num(d.count()) {}

  int num = n;
};

template <int n> bool operator==(MyClass<n> lhs, MyClass<n> rhs) {
  return lhs.num == rhs.num;
}

int main(int argc, char *argv[]) {
  using namespace std::literals::chrono_literals;

  MyClass<0> m1(10ns);

  if (m1 == 10ns)
    cout << "Yay!" << endl;
  return 0;
}

gcc gives this error to reject my overload:

main.cpp:34:12: error: no match foroperator==’ (operand types are ‘MyClass<0>’ andstd::chrono::nanoseconds {aka std::chrono::duration<long int, std::ratio<1l, 1000000000l> >}’)
     if (m1 == 10ns)
         ~~~^~~~~~~
main.cpp:23:6: note: candidate: template<int n> bool operator==(MyClass<n>, MyClass<n>)
 bool operator == (MyClass<n> lhs, MyClass<n> rhs)
      ^~~~~~~~
main.cpp:23:6: note:   template argument deduction/substitution failed:
main.cpp:34:15: note:   ‘std::chrono::duration<long int, std::ratio<1l, 1000000000l> >’ is not derived from ‘MyClass<n>’
     if (m1 == 10ns)
               ^~~~

Is there any way to make this work?

+4
source share
2 answers

An easier way is to put the function in a class:

template <int n> struct MyClass {
  MyClass() = default;

  template <typename REP, typename PERIOD>
  constexpr MyClass(const std::chrono::duration<REP, PERIOD> &d) noexcept
      : num(d.count()) {}

    friend bool operator==(MyClass lhs, MyClass rhs) { return lhs.num == rhs.num; }


  int num = n;
};

Demo

+8
source

This does not work:

if (m1 == 10ns)

, operator== MyClass<0> std::chrono::duration<???, std::nano>, :

template <int n>
bool operator==(MyClass<n> lhs, MyClass<n> rhs);

- 10ns MyClass<n> n, . , :

template <int n, class R, class P> bool operator==(MyClass<n>, duration<R,P> );

:

template <int n, class R, class P> bool operator==(duration<R,P>, MyClass<n> );

. , .

operator== , , Jarod42. , , , , , . , m1 == 10ns :

bool operator==(MyClass<0>, MyClass<0>);

10ns MyClass<0>, , . , . .

+5

Source: https://habr.com/ru/post/1672162/


All Articles