0

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 from c++11).

UPDATE

I arrived at a solution as a derivate of the examples provided by the following SO post...

C compiler asserts - how to implement?

1 Answer 1

2

C++11 and above

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]");
};

Before C++11

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.

1
  • Thank you! I will investigate, and if this solution is what I am looking for, then I will give you the check!
    – Zak
    Jun 26, 2018 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.