Search code examples
c++classtemplatesnon-type-template-parameter

How to initialize a template class with a non constant value


I have a template class that needs I need to set the size of using the size of a vector. what is the best way to achieve this? below is a simplified version, I will link to the full class if you need to see it.

template<int maxParams>
class ParameterChangeHandler
{
public:
    inline ParameterChangeHandler()
    {
        //Do Stuff
    };

    //More Inline Methods that use maxparams and paramBitArray

protected:
    unsigned char paramBitArray[(((maxParams)+((8) - 1)) & ~((8) - 1)) / 8]
};


int main()
{
    std::vector<int> myVectorOfParameters = { 1,2,3,4,5 };

    //This is OK
    //ParameterChangeHandler<10> paramChangeHandler;

    //This is what I want
    ParameterChangeHandler<myVectorOfParameters.size()> paramChangeHandler

}

This is for an audio application that I am building using the Wwise SDK, Here is a link to the actual class that is giving me the issue AkFXParameterChangeHandler


Solution

  • What you want isn't possible. Here's what you can do. Pass myVectorOfParameters.size() as an argument to the constructor and use std::vector/std::basic_string instead of unsigned char array so you don't need a constant expression for the size.

    #include <vector>
    #include <cstddef>
    
    class ParameterChangeHandler
    {
    public:
        ParameterChangeHandler(std::size_t const max_size)
          : paramBitArray(max_size) // or reserve and push_back as needed
        {
            // Do Stuff
        };
    
    protected:
        std::vector<unsigned char> paramBitArray;
    };