gpt4 book ai didi

c++ - 是否可以在特定类型的元组上定义扩展方法?

转载 作者:行者123 更新时间:2023-12-02 10:17:48 25 4
gpt4 key购买 nike

我有一个表示3d点坐标的元组。

是否可以在具有特定类型参数的元组上定义“扩展”方法。扩展方法(名为move)将使元组变异并具有枚举值的参数

std::tuple<int, int, int> myPosition;
// what I want to do is:
myPosition.move(Directions::UP);

这可能吗?还是应该为位置定义包装器结构?

最佳答案

基于此answer,我编辑了一种非常酷的技术来满足您的要求:

#include <functional>
#include <iostream>
#include <tuple>

typedef std::tuple<int, int, int> Position;

enum Direction
{
UP = 1,
DOWN = 2,
LEFT = 3,
RIGHT = 4
};

// select any operator that accepts two arguments
void operator>(Position pos, std::function<void(Position)> binded_extension)
{
binded_extension(pos);
}

// the usual method for such task, we will reference to it
void hidden_move(Position pos, Direction dir)
{
std::cout << "Position "
<< std::get<0>(pos) << ' '
<< std::get<1>(pos) << ' '
<< std::get<2>(pos) << ' '
<< "has been moved in direction " << dir << '\n';
}

struct extension_move
{
std::function<void(Position)> operator()(Direction dir)
{
return std::bind(hidden_move, std::placeholders::_1, dir);
}
};

// choose calling name for extension method here
extension_move move = {};

int main()
{
Position myPosition = {1, 2, 3};

/* overloading the dot operator is not that easy...
but we still get pretty similar syntax
myPosition.move(Direction::UP); */
myPosition>move(Direction::UP);

return 0;
}

如您所见,您必须调用 myPosition.move(UP)而不是 myPosition>move(UP)。您甚至可以选择其他运算符,例如 |^

关于c++ - 是否可以在特定类型的元组上定义扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61360697/

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