c++ - 调用模板成员函数

标签 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;
}

最佳答案

您的函数 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/

相关文章:

N 维 vector 的 C++ 模板化别名

c++ - 根据枚举成员的值特化模板

c++ - 什么是复制省略和返回值优化?

c++ - 使用 QTableView 时将 QCombobox 选定文本设置为特定数据列

c++ - SDL OpenGL 窗口无响应,透明

c++ - 静态获取成员变量的偏移量

c++ - 为什么 C++ 函数模板在其签名中包含返回类型

jQuery 模板已被弃用?

java - 多态性? C++ 与 Java

c++ - VIM 中 c++ 类标签的确定性导航。 ctags 效果不佳