我试图在类模板中调用对象的成员函数,但无法编译以下代码。我找到了一个帖子 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;
}
最佳答案
您的函数 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
是一个模板,并且您想指定模板参数而不是推导,那么语法就像您提到的问题中的示例一样。
关于c++ - 调用模板成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42192444/