Template Constraints C++

Jorge Ferreira picture Jorge Ferreira · Sep 23, 2008 · Viewed 45.8k times · Source

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:

interface IFoo
{
}


class Foo<T> where T : IFoo
{
}

class Bar : IFoo
{
}

class Simpson
{
}

class Program
{
    static void Main(string[] args)
    {
        Foo<Bar> a = new Foo<Bar>();
        Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
    }
}

Is there a way we can impose constraints for template parameters in C++.


C++0x has native support for this but I am talking about current standard C++.

Answer

Venemo picture Venemo · Apr 8, 2014

If you use C++11, you can use static_assert with std::is_base_of for this purpose.

For example,

#include <type_traits>

template<typename T>
class YourClass {

    YourClass() {
        // Compile-time check
        static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive from BaseClass");

        // ...
    }
}