gpt4 book ai didi

c++ - 如何用 common_type 和模板递归类型重载 operator+

转载 作者:行者123 更新时间:2023-11-30 03:13:49 26 4
gpt4 key购买 nike

我不确定如何描述模板的类型何时是结构本身,如下所示。

template<typename T> struct Point{};
Point<Point<int>> p;

这是定义的行为吗?如果是这样,我不知道实现它的最佳方法,以便我可以返回一个没有错误的 common_type,如下所示。

#include <iostream>

template<typename T> struct Point
{
Point() {}
template<typename U, typename V> Point(const U& u, const V& v): x(u), y(v) {}
T x,y;
};

template<typename T, typename U>
inline Point<typename std::common_type<T, U>::type> operator+(const Point<T>& p, const U& n)
{
return {p.x+n, p.y+n};
}

int main() {
Point<int> p;
Point<double> r1 = p + 1.5; //works
Point<Point<int>> p2;
Point<Point<double>> r2 = p2 + 1.5; //error
return 0;
}

错误是:
no match for ‘operator+’ (operand types are ‘Point<Point<int> >’ and ‘double’)

最佳答案

如果你想让它工作(在我看来它不应该,但这取决于你),你可以使用 decltype(std::declval<T>()+std::declval<U>())而不是 std::common_type<...> .

#include <iostream>

template<typename T> struct Point
{
Point(): x{}, y{} {}
template<typename U, typename V> Point(const U& u, const V& v): x(u), y(v) {}
T x,y;
};

template<typename T, typename U>
inline Point<decltype(std::declval<T>()+std::declval<U>())> operator+(const Point<T>& p, const U& n)
{
return {p.x+n, p.y+n};
}

template<typename T>
std::ostream &operator<<(std::ostream& os, const Point<T>& p)
{
os << "Point<" << typeid(T).name() << ">(x=" << p.x << ", y=" << p.y << ")";
return os;
}

int main() {
Point<int> p;
auto r1 = p + 1.5;
Point<Point<int>> p2;
auto r2 = p2 + 1.5;
std::cout << p << "\n";
std::cout << r1 << "\n";
std::cout << p2 << "\n";
std::cout << r2 << "\n";
return 0;
}

我还添加了一个重载打印点。由于 C++ 标准无法保证 typeid(T).name() 是什么会给你可能会看到一些不同的东西,但这就是我得到的:

Point<i>(x=0, y=0)
Point<d>(x=1.5, y=1.5)
Point<5PointIiE>(x=Point<i>(x=0, y=0), y=Point<i>(x=0, y=0))
Point<5PointIdE>(x=Point<d>(x=1.5, y=1.5), y=Point<d>(x=1.5, y=1.5))

Point<i>Point<int> , Point<d>Point<double> , Point<5PointIiE>Point<Point<int>> , 和 Point<5PointIdE>Point<Point<double>> .请注意,我使用了 auto对于 r1r2因此类型由编译器推导。

同样,您是否认为这种行为对您的类(class)有意义取决于您。

关于c++ - 如何用 common_type 和模板递归类型重载 operator+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58402036/

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