Is it possible to check this:
template<class IntType,IntType value>
struct X{};
What I mean by this is, is it possible to check that value supplied by user will "fit" into IntType (which can be any of std integer types) type? For example, I would like to detect something like this:
X<char,300> a;//here 300 is out of range and I would like to be able to detect that.
Now that you've changed
X
's signature from the way it was in the original unedited question, it's easily implemented using Boost.Integer:I would say that the direct solution to this question might be this:
Applied to the OP:
Which renders really terrible CL error messages when it does the job:
While much less snazzy but most comfortable API might be:
Boost is the right way, but want you really want is what is coming the new C++0x standard: static asserts. Boost already implements it in boost_staticassert.
No. Given your code,
300
is converted to achar
by the compiler before you ever get to see it.The closest thing you can do is accept the argument into an integer parameter who's range is larger than your target type. Then check that the value will fit before converting. The only problem is
signed
versusunsigned
, for which I don't think there's a general solution.But not to worry: it's not your class's job to make sure the arguments are being supplied correctly; that would be the job of a utility type that simply doesn't exist. For better or for worse, C++ doesn't provide a clean mechanism for this because it assumes the programmer won't make these mistakes.