首页 > 解决方案 > 自定义数学向量实现中不存在从 vec2f 到 vec5f 的适当转换

问题描述

考虑以下代码段

template <class T, size_t N,
         typename std::enable_if_t<(std::is_arithmetic_v<T> && N > 0), bool> = true>
class vec {
public:

    // ...

    template <class... U,
              typename std::enable_if_t<(sizeof...(U) <= N &&
                                         (std::is_same_v<T, U> && ...)),
                                        bool> = true>
    explicit vec(U&&... args) : scalars({std::forward<T>(args)...}) {
    }

    template <class U, size_t M>
    explicit vec(const vec<U, M>& other) {
        std::copy(other.begin(), other.end(), begin());
    }

    template <class U, size_t M>
    auto& operator=(const vec<U, M>& other) {
        if (this == &other) return *this;
        std::copy(other.begin(), other.end(), begin());
        return *this;
    }

    // ...

    [[nodiscard]] constexpr auto begin() const noexcept { return scalars.begin(); }
    [[nodiscard]] constexpr auto begin() noexcept { return scalars.begin(); }
    [[nodiscard]] constexpr auto end() const noexcept { return scalars.end(); }
    [[nodiscard]] constexpr auto end() noexcept { return scalars.end(); }
private:
    std::vector<T, N> scalars{};
};

尝试像这样执行复制:

vec<float, 2> v2(0.1f, 0.3f);
vec<float, 5> v5 = v2;

导致错误:[不存在从“vec<float, 2ULL>”到“vec<float, 5ULL>”的合适的用户定义转换]

注意:这只是代码片段。我知道有很多数学库可以更好地实现数学向量,我写这个只是为了学习。我知道“四大规则(半)”的规则,但我不知道如何交换两个不同大小的 std::arrays。

标签: c++operator-overloading

解决方案


推荐阅读