未模板类中的模板化函数

时间:2015-04-14 16:22:49

标签: c++ templates

我想在一个没有模板化的类中创建一个模板化函数。

class TheClass
{
    template<typename T>
    int doSomething(T thing);
}

template<typename T>
int TheClass::doSomething(T thing)
{
    ....
}

我不知道为什么会收到错误&#34;会员未找到&#34;当我在课堂外宣布它时。

1 个答案:

答案 0 :(得分:0)

在C ++类中,除非给出“public:”关键字,否则默认其成员变量和方法是私有的。如果您尝试声明/初始化TheClass并在类之外使用doSomething方法,则需要使其可访问。将其公开是使方法可访问的最简单方法,但还有其他方法。您还会在注释中提到的类定义末尾缺少分号。其他一切看起来都不错。

这是一个有效的例子。

#include <iostream>

class TheClass
{
  public:
    template<typename T>
    int doSomething(T thing);
};

template<typename T>
int TheClass::doSomething(T thing)
{
  std::cout << "doSomething(T thing)\n";
  return 0;
}

int main() {
  TheClass x;
  return x.doSomething(5);
}

Running the Program from console:
$ g++ class.c++ -o class
$ ./class

doSomething(T thing)

相关问题