Suppose I have following template
template<unsigned char I, unsigned char F>
class FOO
{
....
}
In fact, I require (I >= F). If someone misuses
FOO<1, 2> a;
I hope to raise a compiling error. How to do that?
Thanks
Template Constraints C++. In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints: Is there a way we can impose constraints for template parameters in C++.
Type parameters can also be used as constraints in generic class definitions. The type parameter must be declared within the angle brackets together with any other type parameters: C#. //Type parameter V is used as a type constraint. public class SampleClass<T, U, V> where T : V { }
Constraints inform the compiler about the capabilities a type argument must have. Without any constraints, the type argument could be any type. The compiler can only assume the members of System.Object, which is the ultimate base class for any .NET type. For more information, see Why use constraints.
The type argument must have a public parameterless constructor. When used together with other constraints, the new () constraint must be specified last. The new () constraint can't be combined with the struct and unmanaged constraints.
One way may be C++11's static_assert
, which is similar to an assert
, but checked at compile time:
template<unsigned char I, unsigned char F>
class FOO
{
static_assert(I >= F, "I needs to be larger or equal to F");
...
};
If you don't have C++11, the good old array bounds trick works here too. Just put the following in the private section of your class:
static int const error_size = I >= F ? 1 : -1;
typedef char ERROR_I_must_not_be_less_than_F[error_size];
This will trigger a "negative array size" error whenever I
is less than F
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With