【发布时间】:2017-08-03 12:41:58
【问题描述】:
我有一个类模板,它的构造函数采用 std::chrono::duration,因为我希望能够使用 chrono_literals 来构造它。现在,我正在尝试定义一个非成员运算符重载,但我无法让它与持续时间构造函数一起使用:
#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 因拒绝我的重载而给出此错误:
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)
^~~~
有什么办法可以做到吗?
【问题讨论】:
-
这需要模板推导、用户定义的转换和重载解析的特定组合。而且它们不会按照此代码要求的顺序发生。
标签: c++ c++11 templates operator-overloading c++14