newprogrammer
newprogrammer

Reputation: 2604

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.

Upvotes: 1

Views: 28

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275946

Within template<...> class X, the name X as a non-template refers to X<...>.

So that <T> is redundant there. It is legal, but redundant.

Upvotes: 2

Related Questions