static_assert on initializer_list :: size() [英] static_assert on initializer_list::size()
问题描述
例如,以下代码:
template< class T,int Length>
class Point
{
public:
Point(std :: initializer_list< T> init)
{
static_assert(init.size长度,尺寸数错误);
}
};
int main()
{
Point< int,3> q({1,2,3});
return 0;
}
会出现以下错误:
test.C:在构造函数'Point< T,Length> :: Point(std :: initializer_list< _Tp>)[with T = int,int Length = 3] :
test.C:60:26:从这里实例化
test.C:54:7:错误:静态断言的非常量条件
test.C:54:73:in constexpr扩展'init.std :: initializer_list< _E> :: size [with _E = int,std :: initializer_list< _E> :: size_type = long unsigned int]()'
test.C:54: 7:错误:'init'不是常量表达式
请注意,示例:
class A
{
public:
constexpr int size(){return 5; }
};
int main()
{
A a;
static_assert(a.size()== 4,oh no!);
return 0;
}
问题,而不是init.size()。
我猜,构造函数可以从不同的地方用不同的长度初始化。
(详细说明:你试图写一个取决于变量的运行时值的 static_assert
code> init ,即它有多少个元素。 static_assert
必须在编译函数时被赋值。类似于这个无效的例子:)
void foo(int i){static_assert(i == 42, ; }
int main(){foo(42); } //但是如果在另一个翻译单元中有一个调用者呢?
Why is std::initializer_list<_E>::size not allowable in a static_assert, even though it's declared as a constexpr in my libstdc++ (v. 4.6)?
For example, the following code:
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;
}
gives the following error:
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
Note that this works just fine for a trivial example:
class A
{
public:
constexpr int size() { return 5; }
};
int main()
{
A a;
static_assert(a.size() == 4, "oh no!");
return 0;
}
The compiler says that init is the problem, not init.size().
I guess that the constructor could be called from different places with different length initializers.
(To elaborate: You're trying to write a static_assert
that depends on the run-time value of the variable init
, namely how many elements it has. static_assert
s have to be evaluable at the time the function is compiled. Your code is analogous to this trivially invalid example:)
void foo(int i) { static_assert(i == 42, ""); }
int main() { foo(42); } // but what if there's a caller in another translation unit?
这篇关于static_assert on initializer_list :: size()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!