Let's say we have a template class which takes non-type arguments. Is it possible to throw a
compiler error presenting the user with an informative error message if the user happens to pass a
specific argument which is considered invalid in the class' design?
Some tricks can be played, but since there is no "custom error message"
that one can push into the compiler, the possibilities are limited.
Example can be an attempt to define an array of a zero or negative size,
the name of which you can use to indicate to the user that the value is
outside of bounds...
// let's say you want to limit the parameter to the range [100,200]
// (inclusive)
template<int a, int b> struct verify_smaller {
enum first_arg_must_be_smaller_than_second { OK = (b > a) };
};
template<int a, int b> struct verify_greater {
enum first_arg_must_be_greater_than_second { OK = (a > b) };
};
template<int a, int b> struct verify_nosmaller {
enum first_arg_must_be_smaller_than_second { OK = (a >= b) };
};
template<int a, int b> struct verify_nogreater {
enum first_arg_must_be_nogreater_than_second { OK = (a <= b) };
};
template<int i, int low, int high> struct verify_in_range
{
enum { OK = (verify_smaller<low,high>::OK
&& verify_nosmaller<i, low>::OK
&& verify_nogreater<i, high>::OK) };
};
template<int i> class mytemplate
{
char (& requirements())[verify_in_range<i, 100, 200>::OK];
};
int main()
{
mytemplate<150> ok_One;
mytemplate<100> ok_Two;
mytemplate<200> ok_Three;
mytemplate<0> not_OK; // produces error
mytemplate<1000> not_OK2; // produces error
}
I am sure you can come up with a simpler way.
V