0

When I compile the following:

#include <iostream>

class A {
public:
    template <class X, class Y>
    void foo(X& x, Y& y) {
        x.bar<Y>(y);
    }
};

class B {
public:
    template <class Z>
    void bar(Z& z) {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

class C {
};

int main() {
    A a;
    B b;
    C c;
    a.foo<B, C>(b, c);
}

I get this:

deduce.cpp: In member function ‘void A::foo(X&, Y&)’:
deduce.cpp:7:10: error: expected primary-expression before ‘>’ token
   x.bar<Y>(y);
          ^

If I don't specify the template parameter and let GCC deduce the template parameter of B::bar(), GCC happily compiles it.

At first, I thought, it means I shouldn't specify a template parameter for a template member function if compiler can deduce it.

However, when I call a.foo(), compiler should be able to deduce the template parameters as well. But compiler doesn't complain about.

Hence, I am confused when specifying template parameters for a template member function is illegal, and when it is a must.

Thanks in advance.

P.S. I am using g++ 7.2.1.

Hei
  • 1,844
  • 3
  • 21
  • 35
  • @StoryTeller I failed to see the similarity between my issue and the post you mentioned. Do you mind elaborating? Thanks! – Hei Mar 04 '18 at 13:24
  • Just read the accepted answer. You can skip to "the template keyword". – StoryTeller - Unslander Monica Mar 04 '18 at 13:28
  • I read the accepted answer. I think the problem there was that the expressions were ambiguous to the compiler and so clarification is needed. I fail to see the ambiguity in my expression above. Any more hint? – Hei Mar 04 '18 at 13:42
  • Yes, C++ doesn't wait for there to be actual ambiguity, it demands of you to be specific, always, with dependent names. I believe that's covered to by one of the other answers. Been awhile since I read them all. – StoryTeller - Unslander Monica Mar 04 '18 at 13:43

0 Answers0