Both C++ templates and C# generics serve a similar purpose. But where C# uses constraints to enable generics, C++ instead uses the compiler to enable templates. And C++ includes the ability to create templates base on values which will enable you to do things unheard of in C#. Most C# developers don’t even know what they’re missing.

When you declare a generic class in C#, you need to specify constraints so that the compiler can figure out if the types that you’re trying to use with the generic class actually meet the requirements or not. If you forget a constraint, then it’s possible to compile code that won’t run. And if you add too many constraints, then it’s possible to generate unnecessary compile errors.

C++ doesn’t use constraint. Instead it looks at how the types are actually used and makes sure that a type has all the methods needed by the template. So if you want to use a class as a template parameter, then just look at how the type T, or whatever it’s called in the template, is actually used and make sure that your class would be able to fit. That’s all there is to it. The compiler will make sure that your template parameters meet the needs of the template class.

You can also specify a value for your template parameters in C++. This allows you to create distinct types that are slightly different. Maybe you want a door that always opens in vs. another door that always opens out. Instead of creating two door classes, an inDoor and an outDoor, just create a single template door class that takes a bool value to select the direction. The compiler will keep your door class as its own type and make sure that it’s a different type than a door class.