How to initialize variable template at template class instantiation

577 Views Asked by At

Suppose that I have this code:

// header file

template < std::unsigned_integral size_type = uint32_t >
class Foo
{
public:
    inline static constexpr size_type max { 168 };
};


// source file

// definitions of class's function templates


// call site

template class Foo<uint8_t>;

As you can see, I'm looking for a way to let the user (i.e. the coder) assign an arbitrary value to max when instantiating Foo. For example 255 (the max for uint8_t) etc. Maybe like this:

template class Foo<uint8_t, 255>;

How is this possible? I have also looked at variable templates but I don't know how to make it work in a readable and elegant way.

Also is there a way to separate the static member variable from the class definition and move it to the source file? Because this variable that I'm trying to deal with is related to the implementation of the class and not its interface. I have 4 of these variables and so I don't know how to make it work meanwhile keeping the code readable.

1

There are 1 best solutions below

6
273K On

Your aim is unclear. Do you want something like this, non-type template parameter with a default value?

#include <concepts>
#include <cstdint>
#include <limits>

template <std::unsigned_integral size_type = uint32_t,
          size_type m = std::numeric_limits<size_type>::max()>
class Foo {
 public:
  inline static constexpr size_type max { m };
};

Foo f0;
Foo<uint8_t> f1;
Foo<uint8_t, 127> f2;
static_assert(Foo<uint8_t>::max == Foo<uint8_t, 255>::max);