Search code examples
c++templatesstdarray

How to have array size depending on parameter in class using template


I have a graph consisting of Q-tuples, where Q is either 3 or 6. The nodes in the graph are modeled as typedef std::array<int,3> NODE or typedef std::array<int,6> NODE respectively. To be more flexible I used a template class

template <int Q>
class DARP
{
// some attributes
    int capacity = Q;
    typedef std::array<int,Q> NODE;
    NODE depot;
    void create_nodes();
};

However, the following implementation results in an error.

template <int Q>
void DARP<Q>::create_nodes()
{
    if (capacity == 3)
        depot = {0,0,0};
    else
        depot = {0,0,0,0,0,0};  
}

This can be fixed by

template <int Q>
void DARP<Q>::create_nodes()
{
    for (int i=0; i<Q; i++)
    {
        depot[i] = 0;
    }
}

but when I'd like to create more complicated nodes like {0,1,4,8,9,10} it would come in handy to be able to write it in this "short" form. Is there any way to handle this more elegantly?


Solution

  • You can use Constexpr If (since C++17) with template parameter Q as:

    if constexpr (Q==3)
        depot = {0,0,0};
    else
        depot = {0,0,0,0,0,0};  
    

    According to the condition value, the statement-true or statement-false will be discarded and then won't cause the error.

    Before C++17, you can specify create_nodes as:

    template <>
    void DARP<3>::create_nodes()
    {
        depot = {0,0,0};
    }
    template <>
    void DARP<6>::create_nodes()
    {
        depot = {0,0,0,0,0,0}; 
    }