honey the codewitch
honey the codewitch

Reputation: 341

Is there a way to force a template argument within a certain range?

Forgive me, as I've tried searching and maybe I'm just using the wrong keywords. I'm almost positive there is a way where I can bound an integer template argument to a positive value. I just know from bitter experience that it's probably not intuitive at all.

Just so you know, STL widgets for doing this (if there are such animals) are pretty much off the table because as much as I love the STL I can't use the STL for the code I'm targeting outside minor stuff like definitions because a lot of the platforms I'm targeting with this code don't have it available. (32kb machines and such)

basically what I want is this

template<const size_t TCapacity /* bounded to a minimum of one */ > class Buffer {
...
};

Where a compile error is thrown if TCapacity is zero such that

Buffer<0> buffer; // won't compile

I mean, not only do i think i have encountered this sort of sorcery before, I've seen things like the Spirit framework do much more complicated things so I'm pretty sure there's an answer. I just doubt it's obvious.

Thanks in advance!

Upvotes: 0

Views: 558

Answers (2)

bipll
bipll

Reputation: 11940

template<std::size_t cap> requires(cap >= 1) class Buffer;

I doubt it can be very reliably doable in C++11. Of course, you can use some pre-concepts SFINAE, like

template<std::size_t cap, class = std::enable_if_t<(cap > 0)>> class Buffer;

or even something more contrived, like

template<std::size_t cap> class Buffer
    : private std::enable_if_t<(cap > 0)
                               , std::integral_constant<std::size_t, cap>>> {};

but they can be overcome quite easily with things like

template<> class Buffer<0> {};

Upvotes: 2

Bob__
Bob__

Reputation: 12779

In C++11, you could just use a static_assert inside the class:

template<std::size_t TCapacity> class Buffer
{
    static_assert(TCapacity > 0, "The size must be greater than zero");
    // ...
};

If the expression is true, this declaration has no effect. Otherwise a compile-time error is issued, and the text is included in the diagnostic message.

Upvotes: 4

Related Questions