Home > Back-end >  Prevent templated class from using itself as instance
Prevent templated class from using itself as instance

Time:11-13

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;

CodePudding user response:

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
}

CodePudding user response:

You might still provide partial specialization to have error in that case:

template <typename T>
constexpr bool always_false = false;

template<class T>
class Foo<Foo<T>>
{
    static_assert(always_false<T>);
};
  • Related