我试图在类模板中调用对象的成员函数,但无法获取以下代码进行编译。我在这里找到了可以使用的帖子object.template method<T>();
。
使用MSVC 2015,我得到错误C2059:语法错误:'模板'
#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;
}
您的函数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
是模板,并且您想指定模板参数而不是推导,那么语法将类似于您提到的问题中的示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句