Can a template class alias itself without specifying its template parameters twice?

Viewed 29

I'm trying to define a new class template which has many parameters. For writing some methods (such as overloaded operators), I'd like to alias the template class type. Right now I'm doing it like this:

template <class T, int a, int b, int c, int d, int e, int f>
class ExampleClass {

  using ExampleClassType = ExampleClass<T, a, b, c, d, e, f>;

  // for example,
  ExampleClassType operator+(const ExampleClassType& rhs) {
    // ...
  }

};

This approach seems redundant, since I'm writing out the list of template parameters twice. Is there a better way? I naively tried

using ExampleClassType = decltype(*this);

but this doesn't work, I think since this is not known at compile time.

Apologies if this is a duplicate question, I tried searching but found nothing about this specifically.

1 Answers

You can actually just use ExampleClass for this purpose. It's called the injected class name and inside the class definition you can use it and it will implicitly be the fully instantiated class.

Example:

#include <iostream>

template<class T, int a>
struct ExampleClass
{
    ExampleClass operator+(const ExampleClass& t_rhs) const { std::cout << a << '\n'; return *this; }
};


int main(int argc, char** argv){
    ExampleClass<int, 7> myClass;
    auto foo = myClass + myClass;
}

See on godbolt.

This will output 7 because in my operator+, ExampleClass was actually used as an injected class name and meant ExampleClass<int, 7>.

Related