1

I am trying to call a member function of an object in a class template, but I cannot get the following code to compile. I found a post here that said I can use object.template method<T>();.

Using MSVC 2015, I get error C2059: syntax error: 'template'

#include <iostream>

class Bar
{
public:
    Bar() : m_x(0.f) { }
    ~Bar() { }

    void setX(double x) { m_x = x; }
    void printX(void) { std::cout << m_x << std::endl; }

private:
    double m_x;
};

template <class T>
class Foo
{
public:
    Foo() { }
    ~Foo() { }

    void setBar(T bar) { m_bar = bar; }
    void printBar(void) { m_bar.template printX<T>(); } // This is the issue

private:
    T m_bar;
};

int main()
{
    Bar bar;
    bar.setX(20.f);
    bar.printX();

    Foo<Bar> foobar;
    foobar.setBar(bar);
    foobar.printBar();

    return 0;
}
Community
  • 1
  • 1
taurous
  • 177
  • 7
  • 4
    As written, Bar doesn't seem to have any templated member functions. –  Feb 12 '17 at 19:53
  • The link you provided is only relevant when the member function being called is a template member function, which yours is *not*. In fact, `printX` is neither a template member function, or a member of a class template (`Bar` is not a template class). In short, that link isn't relevant to whatever problem you're actually having. – WhozCraig Feb 12 '17 at 20:01

1 Answers1

1

Your function printX is not a member template function. Why do you try to call it as a template?

//                          ,--- Not a template, so you must use
//                          v    You must use the function like any other function 
void printBar(void) { m_bar.printX(); }

The template keyword is used with member function template of a dependent type. If the function printX was a template and you would like to specify the template argument instead of deduction, then the syntax would just like the example in the question you mentioned.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • Silly me, I just assumed from the start that trying to call a function from a template would cause an error because it doesn't know that "T" has that method. Thanks for your help, I need to lay off the assumptions and just try stuff. – taurous Feb 12 '17 at 20:00