c++ - VS2015中,{1,2,3}能转换成constexpr std::initializer_list<int>吗?
PHPz
PHPz 2017-04-17 15:07:16
0
2
620

我看到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的问题。

PHPz
PHPz

学习是最好的投资!

reply all(2)
Ty80

About

static_assert(assert_elementof<int>({ 1,2,3 }, 3), "eee");

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

template<class T>
constexpr bool assert_elementof(std::initializer_list<T> v, int N)
{
    //static_assert(N == v.size(),"xxx");
    return N == v.size();
}

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:

constexpr int scale(int N) {return N * 2; }

int main()
{
    int arr[scale(2)];
    int i = 2;
    int arr2[scale(i)];//这里应该会报错,虽然G++不报错。
    return 0;
}

Refer here for the reason why no error is reported

阿神

It should be no problem, remember to add the header file

#include <initializer_list>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!