首页 > 解决方案 > 是否可以在特定类型的元组上定义扩展方法?

问题描述

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

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

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

这可能吗?或者我应该为位置定义一个包装器结构?

标签: c++

解决方案


基于这个答案,我编辑了一种非常酷的技术来满足您的要求:

#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). 您甚至可以选择其他运算符,例如|^


推荐阅读