Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise size of std::array in a constructor of the class that uses it

Is it possible to use the std::array<class T, std::size_t N> as a private attribute of a class but initialize its size in the constructor of the class?

class Router{
    std::array<Port,???> ports; //I dont know how much ports do will this have
public:
    Switch(int numberOfPortsOnRouter){
        ports=std::array<Port,numberOfPortsOnRouter> ports; //now I know it has "numberOfPortsOnRouter" ports, but howto tell the "ports" variable?
    }
}

I might use a pointer, but could this be done without it?

like image 647
Slazer Avatar asked Dec 05 '22 14:12

Slazer


1 Answers

You have to make your class Router a template class

template<std::size_t N> 
class Router{
    std::array<Port,N> ports; 

...
}

in case you want to be able to specify the size of ports at Router level. By the way, N must be a constant known from compile time.

Otherwise you need std::vector.

like image 116
Acorbe Avatar answered Dec 09 '22 15:12

Acorbe