我看到vs2015中的std::initializer_list已经声明成constexpr了。
那么
template<class T>
constexpr bool assert_elementof(std::initializer_list<T> v, int N)
{
//static_assert(N == v.size(),"xxx");
return N == v.size();
}
int main()
{
constexpr int v[] = { 1,2,3 };
static_assert(assert_elementof<int>(std::initializer_list<int>(v, v + sizeof(v) / sizeof(v[0])), 3), "eee");
//static_assert(assert_elementof<int>({ 1,2,3 }, 3), "eee");
return 0;
}
我的是问题,为什么上面两处注释掉的代码不能在VS2015下编译通过?是我的代码有问题呢,还是VS2015的问题。
About
Since the first parameter of static_assert must be a const expression, for constexpr bool assert_elementof(std::initializer_list<T> v, int N), its return value is only when both parameters are const. It's const. So the two parameters {1,2,3}, 3 are constants, so there is no problem in this paragraph.
About
Why does it not work if you remove that comment? Because N is a variable, not a constant expression, so it violates the requirements of static_assert: the first parameter must be a const expression.
There is an excerpt from the c++ primer as follows:
Refer here for the reason why no error is reported
It should be no problem, remember to add the header file