c++ - 可变参数模板 C++ 中的 sizeof

标签 c++ templates variadic

我需要知道可变参数模板的参数包中有多少项。

我的代码:

#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;
}

我在 A 行遇到编译错误。
如果将此行更改为

static const unsigned short int size = sizeof...(Arguments)

可以编译。我的第一个问题是为什么我需要“static const unsigned short”来编译。 如您所见,我需要一个大小来放入我的数组中。我的最终目标是能够在主函数中打印出这个数组。

请帮忙。谢谢.. 我的理想来自这个网站,但我不知道如何让它发挥作用 http://thenewcpp.wordpress.com/2011/11/23/variadic-templates-part-1-2/

最佳答案

根据评论,我认为这是 g++ 处理成员变量的新类内初始化的错误。如果将代码更改为

template <int... Entries>
struct StaticArray
{
    static const int size = sizeof...(Entries); // works fine
};

然后它就可以正常工作了,因为它使用了 C++03 的特殊情况,即在类中初始化 static const 整数成员。

同样,如果您使用新的 C++11 统一初始化语法,它也能正常工作:

template <int... Entries>
struct StaticArray
{
    int size{sizeof...(Entries)}; // no problem
};

我很确定这里的赋值形式是有效的,所以我认为 g++(我的系统上是 4.8.2)弄错了。

(当然,大小不能在运行时改变,所以正确的声明可能是 static constexpr std::size_t size 无论如何,避免这个问题......)

关于c++ - 可变参数模板 C++ 中的 sizeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152667/

相关文章:

c++ - 在 omnet++ IDE 中找不到 -lC :\SQLAPI\lib\sqlapi. 库

c++ - std::function 和 std::bind: 它们是什么,应该在什么时候使用它们?

c++ - 为什么此代码会出现错误 "template specialization requires ' template< >'"?

c++ - 如何让 Maliit 键盘在 Linux 上工作? (薄荷)

c++ - C++ 中的模板化静态成员函数

google-app-engine - 访问 golang 模板中引用对象的属性(Google 应用引擎)

c++ - 消除可变类层次结构中无参数函数调用的歧义

c++ - 使用可变参数模板作为属性

c++ - 如何简化这些可变函数?

c++ - 比较链表,C++,顺序相同但可以不同