Search code examples
c++templatesstandard-library

Make std:array size depending on class template parameter


Let's consider following very simplified example

#include <array>
template<typename T, F>
class GenericColor {
protected:
   std::array<T, F> components;
}

class RGB : public GenericColor<int, 3> { // three components, red, green...
}

class CMYK : public GenericColor<int, 4> { // four components, cyan, magenta....
}

My question is how to make second parameter pointing on std::array size, just to make this example working.


Solution

  • The declaration of std::array is*

    template<class T, std::size_t N> struct array
    

    which tells you exactly how to write your code:

    template<typename T, std::size_t F>
    class GenericColor {
    protected:
       std::array<T, F> components;
    }
    

    *there's some inane details here that it's not required to be exactly that but blah blah blah not relevent.