1
votes

i am using a boost::array which has the format < char, const std::size_t >

void test(const std::size_t XXX)
{
    boost::shared_ptr<boost::array<unsigned char, XXX>> buf(new boost::array<unsigned char, max_size>);
    .
    .
    .
};
test(100);
test(20);

This is leading

to the Error:

error C2971: 'boost::array' : template parameter 'N' : 'size' : a local variable cannot be used as a non-type argument

Can you give me a hint how to pass boost::array the second parameter?

thanks

4
Or for that matter vector<unsigned char> - by the looks of the code, I'd guess that buf is not intended to outlive the call to test, so shared ownership isn't needed. The only way it would be is if test stores it to some long-lived object (like a global, or this if test is a member function). - Steve Jessop

4 Answers

6
votes

Templates are instantiated during the compilation, so that their parameters have to be known before the program runs.

That means you cannot use a variable as a template parameter. Such a parameters must be constant expressions (constant variables is not enough), addresses of functions or objects with external linkage, or addresses of static class members.

3
votes

The second parameter must be a compile time constant.

You could make test() a template function:

template <size_t max_size> void test()
{
    boost::shared_ptr<boost::array<unsigned char, max_size>> buf(
        new boost::array<unsigned char, max_size>);
}
test<100>();
test<20>();
2
votes

You cannot use a non-compile time value as a template parameter, since templates must be instantiated at compile time.

std::array and boost::array can only be used for statically sized arrays. If you need a dynamically sized array you can use std::vector instead.

And typically you don't need to hold onto a vector with a shared_ptr, just hold it directly:

void test(const std::size_t XXX)
{
    std::vector<char> buf(XXX);
    .
    .
    .
};
test(100);
test(20);

or like hmjd says you can pass XXX a compile time constant.

0
votes

Template value must be compile-time constant, that is literal, constexpr or static const variable.