我将如何在矩阵类中获得此功能? [重复]

问题描述 投票:2回答:2

此问题已经在这里有了答案:

#include <iostream>
#include <array>

template<typename T, std::size_t R, std::size_t C>
class matrix
{
   std::array<T, R * C> m_data;
};

int main() 
{
   matrix<float, 2, 2> a = { 1,2,3,4 }; // COMPILER ERROR!
}

Clang报告存在没有匹配的构造函数

我已经尝试编写表单的构造函数

matrix(std::array<T,R*C> a);

并尝试使用&&进行实验,因为我认为所讨论表达式的右侧是暂时的。这使我有些困惑。正如我们期望的那样,将创建它,然后将其分配给a的值。

c++ class c++11 templates initializer-list
2个回答
3
投票

像注释中提到的其他人一样,您的std::initializer_list<T>类需要一个std::initializer_list<T>构造函数。

matrix

1
投票

您不需要#include <array> // std::array #include <initializer_list> // std::initializer_list #include <type_traits> // std::conjunction, std::is_same #include <utility> // std::forward // traits for checking the types (requires C++17) template <typename T, typename ...Ts> using are_same_types = std::conjunction<std::is_same<T, Ts>...>; template<typename T, std::size_t R, std::size_t C> class matrix { std::array<T, R * C> m_data; public: template<typename... Ts> constexpr matrix(Ts&&... elemets) noexcept { static_assert(are_same_types<Ts...>::value, "types are not same!"); static_assert(sizeof...(Ts) == R*C, "size of the array does not match!"); m_data = std::array<T, R * C>{std::forward<Ts>(elemets)...}; } }; int main() { matrix<float, 2, 2> a{ 1.f,2.f,3.f,4.f }; // now compiles // matrix<float, 2, 2> a1{ 1,2,3,4 }; // error: narrowing conversion! // matrix<float, 2, 2> a1{ 1.f,2.f,3.f, 4 }; // error: types are not same! // matrix<float, 2, 2> a1{ 1.f,2.f,3.f,4.f, 5.f }; // error: size of the array does not match! }

© www.soinside.com 2019 - 2024. All rights reserved.