gpt4 book ai didi

c++ - initializer_list::size() 上的 static_assert

转载 作者:IT老高 更新时间:2023-10-28 12:43:28 25 4
gpt4 key购买 nike

为什么是 std::initializer_list<_E>::size不允许在 static_assert 中使用,即使它被声明为 constexpr在我的 libstdc++ (v. 4.6) 中?

例如下面的代码:

template<class T, int Length>
class Point
{
public:
Point(std::initializer_list<T> init)
{
static_assert(init.size() == Length, "Wrong number of dimensions");
}
};

int main()
{
Point<int, 3> q({1,2,3});

return 0;
}

给出以下错误:

test.C: In constructor ‘Point<T, Length>::Point(std::initializer_list<_Tp>) [with T = int, int Length = 3]’:
test.C:60:26: instantiated from here
test.C:54:7: error: non-constant condition for static assertion
test.C:54:73: in constexpr expansion of ‘init.std::initializer_list<_E>::size [with _E = int, std::initializer_list<_E>::size_type = long unsigned int]()’
test.C:54:7: error: ‘init’ is not a constant expression

请注意,这对于一个简单的示例来说效果很好:

class A
{
public:
constexpr int size() { return 5; }
};

int main()
{
A a;
static_assert(a.size() == 4, "oh no!");

return 0;
}

最佳答案

“初始化列表”只是可怕的杂物。

不要:

#include <initializer_list>

template<typename T>
void Dont(std::initializer_list<T> list) { // Bad!
static_assert(list.size() == 3, "Exactly three elements are required.");
}

void Test() { Dont({1,2,3}); }

做:

template<typename T, std::size_t N>
void Do(const T(&list)[N]) { // Good!
static_assert(N == 3, "Exactly three elements are required.");
}

void Test() { Do({1,2,3}); }

关于c++ - initializer_list::size() 上的 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5438671/

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