简体   繁体   中英

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?

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}; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM