Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template: How to put nontype constraints in compiling time

Tags:

c++

templates

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

like image 232
Yan Zhu Avatar asked Mar 03 '12 07:03

Yan Zhu


People also ask

What are template constraints in C++?

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++.

How to use type parameter as a type constraint?

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 { }

What are constraints in typescript?

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.

Which constraint should be specified last in a type argument?

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.


2 Answers

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");
    ...
};
like image 100
Christian Rau Avatar answered Nov 15 '22 12:11

Christian Rau


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.

like image 26
Xeo Avatar answered Nov 15 '22 13:11

Xeo