0

The following code confuses me:

#include <iostream>

template <typename T>
struct base
{
  T &self()       { return *static_cast<T *>(this); }
  template<typename T1> void method() {
    std::cout << sizeof(T1) << "\n";
  }

  void hello()  {
    self().template method<int64_t>();  // <-- here
    self().template method<int32_t>();  // well, and here too
  }
};

struct derived : base<derived>
{
  void hello2()  {
    self().method<int16_t>();  // seriously???
  }
};

int main(int args, char ** argv) {
  derived d;
  d.hello();
}

This compiles and does what I want. But what is this "template" business on the lines highlighted by comments? What is this syntax even called? And why do i need it? And if I remove the word "template", at least with gcc I get errors:

member.cc: In member function ‘void base<T>::hello()’: member.cc:12:26: error: expected primary-expression before ‘>’ token
     self().method<int64_t>();
                          ^ member.cc:12:28: error: expected primary-expression before ‘)’ token
     self().method<int64_t>();
                            ^

And, last but not least, why does the method derived::hello2() compile just fine without the "template" word?

I should add that it clearly has something to do with base being templated. If i make it a non-templated class and get rid of the self acrobatics, i no longer need the "template" keyword.

MK.
  • 33,605
  • 18
  • 74
  • 111

0 Answers0