【发布时间】:2019-01-22 04:10:37
【问题描述】:
我正在创建一个从 std::array 继承的简单类。关键是如果下标运算符用于越界索引,它应该引发编译时错误。但是,我不断收到错误消息。这是简化的代码。
#include <array>
using namespace std;
template<typename type, size_t size>
struct container : array<type,size>
{
constexpr inline type& operator[](int index) const
{
static_assert(index<size,"");
return ((static_cast<const array<type,size> >(*this))[index]);
}
template<class... bracelist>
constexpr container(bracelist&&... B)
:array<type,size>{std::forward<bracelist>(B)...}
{}
container() = default;
};
int main()
{
constexpr container<int,4> myarray = {5,6,7,8};
constexpr int number = myarray[2];
}
它给我的错误是:
main.cpp|80|error: non-constant condition for static assertion
main.cpp|80|error: 'index' is not a constant expression
但是,我在 return 语句中使用了“index”,并且注释掉了 static_assert 使其工作正常。如果 index 不是常量表达式,我不能在 static_cast 之后的 std::array 的下标运算符中使用它吗?我是使用 constexpr 功能的新手,因此将不胜感激。谢谢。
注意:我知道 std::array 的 constexpr 下标运算符已经做到了这一点,我只是想知道如何做到这一点以备将来使用。谢谢。
【问题讨论】:
-
不幸的是,这不起作用。你可以做
return index >= size ? static_cast<const array<type,size> >(*this)[index] : throw std::runtime_error(""); -
你在使用 C++11 吗?
constexpr inline type &应该是constexpr inline type const &和static_cast<const array<type,size> >应该是static_cast<const array<type,size> & >并且引入类型别名会更好。
标签: c++ arrays constexpr compile-time stdarray