newprogrammer newprogrammer - 2 months ago 10
C++ Question

Template class argument for template class function syntax

template <typename T>
class Foo {
public:
T val;
Foo(T p_val) : val(p_val) {}
T sum(Foo<T> other) { return val + other.val; }
};

int main() {
Foo<int> f1(3);
Foo<int> f2(5);
std::cout << f1.sum(f2) << std::endl;
}


This prints
8
as expected.

If I change the member function signature to
T sum(Foo other)
(removing the
<T>
), it still prints
8
. In general does it matter whether I include that
<T>
or not? I'm using Visual C++ 2015.

Answer

Withing template<...> class X, the name X refers to X<...> by default.

So that <T> is redundant there.

Comments