C++ 可以在特定类型的元组上定义扩展方法吗?

C++ 可以在特定类型的元组上定义扩展方法吗?,c++,C++,我有一个表示三维点坐标的元组 是否可以使用特定的类型参数在此元组上定义“扩展”方法。扩展方法(名为move)将对元组进行变异,并使参数的值为enum std::tuple myPosition; //我想做的是: 移动(方向::向上); 这可能吗?或者我应该为position定义一个包装结构吗?基于此,我编辑了一个非常酷的技术来满足您的需求: #include <functional> #include <iostream> #include <tuple>

我有一个表示三维点坐标的元组

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

std::tuple myPosition;
//我想做的是:
移动(方向::向上);
这可能吗?或者我应该为position定义一个包装结构吗?

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

#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;
}
#包括
#包括
#包括
typedef std::元组位置;
枚举方向
{
UP=1,
向下=2,
左=3,
右=4
};
//选择任何接受两个参数的运算符
无效运算符>(位置位置,标准::函数绑定的扩展名)
{
绑定扩展(pos);
}
//对于这类任务的常用方法,我们将参考它
无效隐藏移动(位置位置、方向方向)
{

std::不可能,这是不可能的。只使用函数有什么错?(C++不迷恋对象。)不要对自定义类型使用元组,这不是它们的目的,通常是个坏主意。定义自定义类型。@molbdnilo是的,这是有意义的,我认为在C#中是可能的,我更喜欢它的可读性是
myPosition.move(方向::向上)
而不是
移动(我的位置,方向::向上)
。将其作为答案发布,我将接受。这是否回答了您的问题?