gpt4 book ai didi

c++ - 如何为类模板定义非成员运算符重载?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:25 25 4
gpt4 key购买 nike

我有一个类模板,它有一个采用 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)
^~~~

有什么方法可以让它工作吗?

最佳答案

更简单的方法是将函数放在类中:

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

关于c++ - 如何为类模板定义非成员运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42764649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com