私はchrono_literalsを使用して構築できるようにするために、std :: chrono :: durationを取るコンストラクタを持つクラステンプレートを持っています。今、私は非メンバ演算子のオーバーロードを定義しようとしているが、私はそれが持続コンストラクタで動作させることはできません。クラステンプレートの非メンバー演算子オーバーロードを定義する方法は?
main.cpp:34:12: error: no match for ‘operator==’ (operand types are ‘MyClass<0>’ and ‘std::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)
^~~~
:
#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が私の過負荷を拒否するため、このエラーを与えています
この作業を行う方法はありますか?
これには、テンプレート控除、ユーザー定義変換、および過負荷解決の特定の組み合わせが必要です。そして、このコードが必要とする順序では起こりません。 –