c++ - 是否可以在特定类型的元组上定义扩展方法?
问题描述
我有一个代表 3d 点坐标的元组。
是否可以使用特定类型参数在此元组上定义“扩展”方法。扩展方法(名为move
)将改变元组并具有 enum 值的参数
std::tuple<int, int, int> myPosition;
// what I want to do is:
myPosition.move(Directions::UP);
这可能吗?或者我应该为位置定义一个包装器结构?
解决方案
基于这个答案,我编辑了一种非常酷的技术来满足您的要求:
#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)
. 您甚至可以选择其他运算符,例如|
或^
。
推荐阅读
- php - 写入数据库,并在同一 PHP 页面加载中检索更新的数据?
- python - 为什么 concurrent.futures 在返回 np.memmap 时会占用内存?
- sql - 2个select语句会导致彼此死锁吗?
- python - 多个子图大小一致的 Matplotlib 颜色条
- javascript - 如何仅在 div 上应用 javascript
- haskell - 如何将 DELETE 请求卷曲到 Yesod?
- integration-testing - 在集成测试中检索连接字符串
- r - 用 R 对数据帧中的缺失数据进行插值
- java - 如何比较 Selenium 中的两个双数
- r - 使用 layout() 进行绘图的 R 代码在逐行执行时有效,但在包含在函数中时无效