Home > Software engineering >  How do I use all instances of a templated class?
How do I use all instances of a templated class?

Time:01-20

So I have a simple template class with multiple classes inheriting different types of it.

template<typename T> class root {
    T value;
};

class body : public root<int> {
    /* some code */
};

/*some more classes that inherits root*/

and later down in the file, I need to reference all classes that inherits from root

concept _bcie = std::is_base_of_v<root, body>

and it gives me the error use of class template 'root' requires template arguments

But I want to reference ALL classes that inherits from the root

Is there a way to just use the class without providing a template argument?

CodePudding user response:

Make root derive from another higher non-template base class, and check against that class.

CodePudding user response:

The simple way is to use template lambda

template<typename T> 
class root {
  T value;
};

template<class T>
concept is_derived_from_root = requires (const T& t) {
  []<class U>(const root<U>&){}(t);
};

Demo

  • Related