Prevent templated class from using itself as instance

Advertisements

Suppose I have a class template

template<class T>
class Foo{};

Is it possible to prevent T from being an instantiation of Foo. That is, this should not compile:

struct Bar{};

Foo<Foo<Bar>> x;

>Solution :

Another option:

#include <type_traits>

template <typename T>
struct ValidFooArg;

template <typename T>
requires ValidFooArg<T>::value
class Foo
{

};

template <typename T>
struct ValidFooArg : std::true_type {};
template <typename T>
struct ValidFooArg<Foo<T>> : std::false_type {};

int main()
{
    Foo<int> x; // ok
    Foo<Foo<int>> y; // error
}

Leave a ReplyCancel reply