thodoris
thodoris

Reputation: 69

c++ initialize char array of size "static * int" in template function

Is it possible to initialise a char array inside a template function with size contained in a static * int?

.header

static int * array_size;

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

Or is there a way to initialize "array_size" so that the template has a default value to use?

Upvotes: 0

Views: 880

Answers (2)

Abubadabu
Abubadabu

Reputation: 194

Qualifyer for array_size must be constant, otherwhise you will end with expected constant expression. Static keyword is irrelevant.

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

Pointer dereferencing will not work even if the pointer points to a const

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

You also might paste in the array_size via a template parameter:

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

f<int, 42>(100);

Upvotes: 0

Marius
Marius

Reputation: 2273

static int * array_size won't work because the data inside the pointer is modifiable and thus cannot be determined at compile-time.

If you are using C++11 I would suggest

constexpr int array_size = 42;

If you cannot use C++11 I would use:

static const int array_size = 42;

In both cases you create your buffer like this:

char buffer[array_size];

So without the asterisk.

If you cannot find out the size of the buffer at compile time (so the size is dependant on runtime-decisions) you need to use a dynamic array, preferably encapsulated into a 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)

Upvotes: 3

Related Questions