std::array 模板的运算符重载?

问题描述 投票:0回答:1

我想要一种简单的方法来将固定大小的浮点数组按元素相乘。我编写了以下代码来尝试实现此目的:

#include <array>
#include <cstdint>

template <uint16_t N>
using color = std::array<float,N>;

template <uint16_t N>
constexpr color<N> operator* (color<N> lhs, const color<N>& rhs)
{
    for (int i = 0; i < N; i++){
        lhs[i] *= rhs[i];
    }
    return lhs;
};

int main()
{
    constexpr uint16_t N = 10;

    color<N> myColor{1,2,3,4,5,6,7,8,9,10};
    color<N> myColor2{2,4,6,8,10,12,14,16,18,20};
    
    color<N> mult = myColor * myColor2;

    return 0;
};

用gcc编译时,出现以下错误:

test.cpp: In function ‘int main()’:
test.cpp:23:29: error: no match for ‘operator*’ (operand types are ‘color<10>’ {aka ‘std::array<float, 10>’} and ‘color<10>’ {aka ‘std::array<float, 10>’})
   23 |     color<N> mult = myColor * myColor2;
      |                     ~~~~~~~ ^ ~~~~~~~~
      |                     |         |
      |                     |         array<[...],[...]>
      |                     array<[...],[...]>
test.cpp:8:20: note: candidate: ‘template<short unsigned int N> constexpr color<N> operator*(color<N>, color<N>&)’
    8 | constexpr color<N> operator* (color<N> lhs, const color<N>& rhs)
      |                    ^~~~~~~~
test.cpp:8:20: note:   template argument deduction/substitution failed:
test.cpp:23:31: note:   mismatched types ‘short unsigned int’ and ‘long unsigned int’
   23 |     color<N> mult = myColor * myColor2;
      |                               ^~~~~~~~

有没有办法拥有运算符重载的模板?或者有更明智的方法来解决这个问题吗?

c++ arrays templates operator-overloading
1个回答
1
投票

uint16_t
不是正确的类型。
std::array
使用
std::size
代表
N
,因此如果您想使用
std::array
,请使用
std::size_t
:

template <std::size_t N>
//        ^^^^^^^^^^^
using color = std::array<float, N>;

template <std::size_t N>
//        ^^^^^^^^^^^
constexpr color<N> operator* (color<N> lhs, const color<N>& rhs)
© www.soinside.com 2019 - 2024. All rights reserved.