具有运算符的std :: array的C ++ 11类型别名

Med*_*ist 2 c++ typedef c++11

我有一个c ++ 11类型别名

using coord = std::array<double, 3>;
Run Code Online (Sandbox Code Playgroud)

我可以为坐标定义运算符+吗?怎么样?我希望能够做到:

coord a, b, c;
a = {1.1, 2.0, 0};
b = {0, -1, 3.5};
c = a + b; // c = {1.1, 1.0, 3.5}
Run Code Online (Sandbox Code Playgroud)

Gui*_*cot 6

我不建议为STL类型或您无法控制的任何类型定义新的运算符。

我建议改为创建自己的类型:

struct coord {
    // reimplement operator[], fill, size, etc.

    friend constexpr auto operator+ (coord const& lhs, coord const& rhs) noexcept -> coord {
        // ...
    }

private:
    std::array<double, 3> _coord;
};
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用已经定义在std::array以下位置的运算符和成员函数来捷径:

struct coord : private std::array<double, 3> {
    constexpr coord(double a, double b, double c) noexcept :
        array{a, b, c} {}

    using array::operator[];
    using array::begin;
    using array::end;
    using array::fill;
    // other operators...

    friend constexpr auto operator+ (coord const& lhs, coord const& rhs) noexcept -> coord {
        // ...
    }
};
Run Code Online (Sandbox Code Playgroud)

注意:如果你想支持结构化的结合,并提供元组就像访问你的coord类,则必须增加对过载get,并专注std::tuple_sizestd::tuple_element

namespace std {
    template<size_t n>
    tuple_element<n, ::coord> {
        using type = double;
    };


    tuple_size<::coord> : integral_constant<size_t, 3> {};
}

template<std::size_t n>
constexpr auto get(coord const& c) noexcept -> double const& {
    return c[n]
}

template<std::size_t n>
constexpr auto get(coord& c) noexcept -> double& {
    return c[n];
}

template<std::size_t n>
constexpr auto get(coord&& c) noexcept -> double&& {
    return std::move(c[n]);
}

template<std::size_t n>
constexpr auto get(coord const&& c) noexcept -> double const&& {
    return std::move(c[n]);
}
Run Code Online (Sandbox Code Playgroud)

当您打开C ++ 17时,此代码将允许这种代码:

auto my_coord = coord{1.0, 2.0, 3.0};
auto [x, y, z] = my_coord;
Run Code Online (Sandbox Code Playgroud)