There is a class I’m refactoring which currently has a method:
void resize(size_t sz)
In the current codebase, sz is always 0,1,2,or 3.
The underlying class is changing from dynamic allocation to a preallocated array of maxsize==3.
How can I get a build time error if someone tries to resize to sz>3 ?
It is easy enough to add a runtime check. But I’d rather get a compile-time check that fails sooner.
I don’t want to change any existing code that makes calls with an integer literal that is in-bounds ,e.g.:
x.resize(2)
should still compile as is.
But if someone comes along and tries to
x.resize(4)
or
x.resize(n)
it should fail to compile or link.
I was thinking about a template specialized on int that is undefined for anything other than {0,1,2,3}. But I’m not sure quite how to make it do what I want within the confines of standard c++.
edit:
I should elaborate on my thoughts of using the template. I am quite willing to change the declaration of the resize function. I am not willing to change the calling code.
e.g. I was thinking something like
void resize( ConstructedFromLiteral<0,3> sz)
or
void resize( ConstructedFromLiteral<0> sz)
void resize( ConstructedFromLiteral<1> sz)
void resize( ConstructedFromLiteral<2> sz)
void resize( ConstructedFromLiteral<3> sz)
There’s no way you can get a compile-time check for a run-time value. Imagine if you said,
How is the compiler supposed to check that?
However, you can make the function a template, since template parameters are known at compile time:
If you don’t have static asserts, you can rig up your own static-assert class that’ll fail to compile:
Usage: