Can a class inherit from another class template concretized by itself?

162 views Asked by At

I was going through some code and I found something like this:

class GarbageCollectorProcess : public process::Process<GarbageCollectorProcess>

I was wondering if this was a valid thing to do. If yes, shouldn't this lead to some kind of a self definition loop because we are defining a GarbageCollectorProcess using another class that depends on the definition of GarbageCollectorProcess?

2

There are 2 answers

0
ForEveR On

It's valid thing to do. This is how CRTP working.

0
πάντα ῥεῖ On

"I was wondering if this was a valid thing to do."

Yes this is valid, and also a very common pattern called Curiously Recurring Template Pattern, or short CRTP.

It's used to implement static polymorphism for instance.

"If yes, shouldn't this lead to some kind of a self definition loop because we are defining a GarbageCollectorProcess using another class that depends on the definition of GarbageCollectorProcess?"

No, there's no self definition loop. The template class is instantiated just once.