sizeof in variadic template c++
I need to know how many items in parameter pack of a variadic templete.
my code:
#include <iostream>
using namespace std;
template <int... Entries>
struct StaticArray
{
int size = sizeof... (Entries);// line A
//int array[size] = {Entries...};// line B
};
int main()
{
StaticArray<1,2,3,4> sa;
cout << sa.size << endl;
return 0;
}
I got compilation error on line A.
if change this line to
static const unsigned short int size = sizeof...(Arguments)
It can be compiled. my first question is why I need "static const unsigned short" to get compiled. as you can see, I need a size to put in on my array. my final goal is able to print this array out in main function.
please help. thanks.. my ideal comes from this website but i dont know how to make it works http://thenewcpp.wordpress.com/2011/11/23/variadic-templates-part-1-2/
As per the comments, I think this is a bug in g++'s handling of the new in-class initialisation of member variables. If you change the code to
template <int... Entries>
struct StaticArray
{
static const int size = sizeof...(Entries); // works fine
};
then it works correctly, because this uses the C++03 special case of initialising static const integral members in-class.
Similarly, if you use the new C++11 uniform initialisation syntax, it works correctly:
template <int... Entries>
struct StaticArray
{
int size{sizeof...(Entries)}; // no problem
};
I'm pretty sure the assignment form is valid here, so I think g++ (4.8.2 on my system) is getting it wrong.
(Of course, the size can't change at run-time, so the correct declaration would probably be static constexpr std::size_t size
anyway, avoiding this problem...)
上一篇: 可变模板函数名称查找无法找到专业化