Reputation: 12653
Here is a grossly over-simplified class:
template <unsigned x>
class myArray {
int getIndex(unsigned i) { return y[i]; }
void setIndex(unsigned i, int v) { y[i] = v; }
private:
int y[x];
};
How would I use template meta-programming to ensure x
is less than 64
(or any arbitrary value)?
I could add the constructor:
myArray () { if (x >= 64) { throw; } }
but that is horrible...
Is there a more elegant way to bound the template parameter, so that it can be checked at compile time, instead of runtime?
NOTE: If this is possible in
c++03
, then I need the syntax in that form (in case it were to differ fromc++11
).
I arrived at a solution as a derivate of the examples provided by the following SO post...
C compiler asserts - how to implement?
Upvotes: 0
Views: 37
Reputation: 1861
In C++11 and above there is the static_assert
declaration for this purpose. Your compiler then checks the condition at compile time. You can use it at class scope in the form
template <unsigned x>
class myArray {
static_assert(x > 0 && x <= 64, "array size in (0, 64]");
};
In pre-C++11 there are workarounds to provide the same functionality as C++11's static_assert
. Most of those workarounds provide a macro based on the following idea: if your check (compile-time expression of type bool
) yields false
then the macro expands to some illegal code that produces a compiliation error. Otherwise, the macro expands to an empty string. Advanced implementations allow one to specify an additional error message. If you want an out-of-the-box solution then you may have a look at BOOST_STATIC_ASSERT
.
Upvotes: 2