调用模板成员函数

时间:2017-02-12 19:50:16

标签: c++ templates

我试图在类模板中调用对象的成员函数,但我无法获得以下代码进行编译。我找到了一篇帖子here,表示我可以使用object.template method<T>();

使用MSVC 2015,我收到错误C2059:语法错误:'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;
}

1 个答案:

答案 0 :(得分:1)

您的函数printX不是成员模板函数。为什么要尝试将其称为模板?

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

template关键字与从属类型的成员函数模板一起使用。如果函数printX是一个模板而你想指定模板参数而不是演绎,那么语法就像你提到的问题中的例子一样。

相关问题