1

This code with and without the .template keyword seems to work fine. I am confused why this is so.

#include <iostream>

using namespace std;
struct MyS{
    int j;
    float y;
    
    template<typename T>
    void foo(T a) {
        T b = (a /T(3)) * T(2);
        cout << "b = " << b << endl;    
    }
};

int main()
{
    MyS M;
    M.j = 44;
    M.y = 34.257;
    M.foo<int>(M.j);
    M.foo<float>(M.j);
    M.template foo<int>(M.y); // no compilation error - works just as well.
    M.template foo<float>(M.y);
    return 0;
}

The output is

b = 28
b = 29.3333
b = 22
b = 22.838
hsane
  • 11
  • 1
  • 3
    Likely duplicate: [Where and why do I have to put the "template" and "typename" keywords?](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) Short answer - you can tell the compiler that `foo` is a template, but in your case, the compiler can also deduce that it's a template. – Drew Dormann Jun 23 '22 at 15:42
  • 1
    You only need `template` when the thing to the left of the `.` is a dependent name. `M` in your case is not, so no `template` is needed to help out the compiler. – NathanOliver Jun 23 '22 at 15:45
  • 1
    The `.template` syntax is only required within a template function/method call. This is due to static analysis for templates. MSVC doesn't require it at all. – ALX23z Jun 23 '22 at 15:45

0 Answers0