gpt4 book ai didi

c++ - 通过接受原始数组引用的 constexpr 构造函数初始化 constexpr 变量时的 MSVC 错误?

转载 作者:行者123 更新时间:2023-12-04 13:24:46 25 4
gpt4 key购买 nike

使用最新的 GCC 和 Clang 稳定版本时,以下代码编译良好。
但是 MSVC 给出了一个错误,即矩阵的初始化不计算为常数。这是一个 MSVC 错误还是我错过了什么?
Live example :

<source>(72): error C2131: expression did not evaluate to a constant
<source>(71): note: failure was caused by out of range index 4; allowed range is 0 <= index < 4
#include <cassert>
#include <cstring>
#include <iostream>
#include <utility>
#include <stdexcept>

struct index_t final
{
constexpr index_t() = default;
constexpr index_t(const std::size_t r, const std::size_t c) :
row{ r },
col{ c }
{
}

std::size_t row{};
std::size_t col{};
};


template<typename type_t, std::size_t rows_v, std::size_t columns_v>
class matrix_t final
{
public:

explicit constexpr matrix_t(const type_t(&values)[rows_v][columns_v])
{
for (std::size_t row = 0; row < rows_v; ++row)
{
for (std::size_t col = 0; col < columns_v; ++col)
{
m_values[row][col] = values[row][col];
}
}
}

constexpr index_t get_index_for_value(const type_t& value) const
{
for (std::size_t row = 0; row < rows_v; ++row)
{
for (std::size_t col = 0; col < columns_v; ++col)
{
if (m_values[row][col] == value)
{
return index_t{ row,col };
}
}
}
throw std::invalid_argument("value not found in array");
}

constexpr auto operator[](const std::size_t row) const
{
return &m_values[row][0];
}


private:
type_t m_values[rows_v][columns_v]{};
};


// Intialization of matrix : error C2131: expression did not evaluate to a constant
// message : failure was caused by out of range index 4; allowed range is 0 <= index < 4
constexpr matrix_t matrix
{ {
{ 18, 39, 91, 91 },
{ 67, 3, 9, 95 },
{ 69, 3, 68, 93 },
{ 69, 21, 92, 92 }
} };

int main()
{
static_assert(matrix[1][1] == 3);
static_assert(matrix.get_index_for_value(68).row == 2);
static_assert(matrix.get_index_for_value(68).col == 2);
return 0;
}

最佳答案

该错误已在此处得到确认 Incorrect-Index-Out-of-Range-Error

关于c++ - 通过接受原始数组引用的 constexpr 构造函数初始化 constexpr 变量时的 MSVC 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69234785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com