非模板化类中的模板化函数

Templated function in untemplated class

本文关键字:函数      更新时间:2023-10-16

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

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

我不知道为什么当我在类外声明它时出现错误"找不到成员"。

在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)