Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent templated class from using itself as instance

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading