【问题标题】:c++ initialize char array of size "static * int" in template functionc ++在模板函数中初始化大小为“static * int”的char数组
【发布时间】:2014-04-10 11:59:08
【问题描述】:

是否可以在模板函数中初始化 char 数组,其大小包含在静态 * int 中?

.header

static int * array_size;

template <class T>
void f(T value)
{
    char buffer[*array_size];
}

或者有没有办法初始化“array_size”,让模板有一个默认值可以使用?

【问题讨论】:

  • 为什么要在这里使用指针? [] 中的表达式必须是常量表达式,因此不能使用可修改类型。 static constexpr int const* array_size = &amp;my_size;(其中my_size 是例如constexpr int)是可能的,但不确定你为什么要使用它。
  • 我正在尝试拥有一个可以更改其大小的缓冲区
  • 数组大小必须在编译时知道。您可以使用 std::vector 代替数组。

标签: c++ arrays templates pointers static


【解决方案1】:

static int * array_size 不起作用,因为指针内的数据是可修改的,因此无法在编译时确定。

如果你使用的是 C++11,我建议

constexpr int array_size = 42;

如果你不能使用 C++11,我会使用:

static const int array_size = 42;

在这两种情况下,您都可以像这样创建缓冲区:

char buffer[array_size];

所以没有星号。

如果您无法在编译时找出缓冲区的大小(因此大小取决于运行时决策),您需要使用动态数组,最好封装到std::vector

std::vector<char> bufferVec(myDynamicSize); // Use any integer you want to
char *buffer = &bufferVec[0]; // Use this buffer as a standard array 
                              // with size myDynamicSize OR use the std::vector
                              // directly (much cleaner)

【讨论】:

    【解决方案2】:

    array_size 的限定符必须是常量,否则将以预期的常量表达式结尾。静态关键字无关紧要。

    const int array_size = 42;
    char buffer[array_size];
    

    即使指针指向 const,指针解引用也不起作用

    const int a = 42;
    int const * const array_size = &a;
    char buffer[array_size]; // error C2057: expected constant expression
    

    您也可以通过模板参数粘贴 array_size:

    template <class T, int array_size>
    void f(T value)
    {
      char buffer[array_size];
    }
    
    f<int, 42>(100);
    

    【讨论】:

    • "即使指针指向 const,指针解引用也不会起作用" 如果 指针 已被声明为 constexpr (在这种情况下)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多