Specifying static and dynamic sizes at compile time

87 views Asked by At

For the moment, I have a class, of the following form:

template <std::size_t N, 
          class T,
          class Allocator = typename std::conditional<N, void, std::allocator<T>>::type>
class myclass {};

Which is a particular container with the following behaviour:

  • if N > 0, then the container has a static size of N, and the Allocator template parameter should be void.
  • if N == 0, then the container is of dynamic size of, and the Allocator parameter will be used.

But I am not satisfied with this design because it does not seem elegant. I would like a solution standard-like or boost-ready. Maybe such a problem has already been encountered for the design of one of the boost libary. If so what solution has been chosen?

Considering the fact that I want to keep a single version of myclass, and not two version static_myclass and dynamic_myclass.

1

There are 1 answers

2
Barry On BEST ANSWER

This might be a good use-case for CRTP. Have a base class which does all the important stuff, which asks its derived class for the actual objects:

template <typename Derived, typename T>
class myclass_base_impl { 
    // generic stuff
    // static_cast to Derived& to get actual data
};

Then, you have two versions of it. The dynamic one:

template <typename T>
class myclass_dynamic 
: public myclass_base_impl<myclass_dynamic<T>, T>
{
    /* stuff that uses std::allocator<T> */
};

And the static one:

template <typename T, size_t N>
class myclass_static
: public myclass_base_impl<myclass_static<T, N>, T>
{
     // presumably something like
    T data_[N];
};