2

I've seen code like the following, and I'm confused about what it means for foo's parameter to be a const A & rather than a const A<T> &. I suspected that maybe this meant that the method can take any A, but it looks like it implicitly means A<T> based on the fact that a1.foo(a2) doesn't compile in the below snippet.

Does A always mean A<T> when it's used for a variable declaration inside a member of A? In what specific circumstances does this hold? I see that I can't make foo's return type A (compile error: use of class template 'A' requires template arguments). Would most C++ programmers use A or A<T> here?

#include <iostream>

template<int T>
class A {
public:
    void foo(const A &a);
};

template<int T>
void A<T>::foo(const A &a) {
    std::cout << T << std::endl;
}

int main(int argc, char **argv) {
    A<1> a1;
    A<2> a2;

    // These compile
    a1.foo(a1);
    a2.foo(a2);

    // This fails to compile because no viable conversion from 'A<2>' to 'const A<1>'
    // a1.foo(a2); 

    return 0;
}
Joe Doe
  • 23
  • 2
  • See the linked answer, but tldr, within `A`, the name `A` refers to `A` (the specific type, not the class template). So `A<1>::foo` takes an `A<1> const&` and `A<2>::foo` takes an `A<2> const&`. Those are different types. – Barry Jan 17 '17 at 18:13
  • I'm still curious about the style issue. Is it good practice to leave out the `` because it's redundant or should it generally be included? – Joe Doe Jan 17 '17 at 18:28
  • I would leave it out, except where needed. Otherwise people will wonder why the template parameter is needed here. – Bo Persson Jan 17 '17 at 19:01

0 Answers0