如何正确声明带有模板类的函数作为标头中的返回类型?

问题描述 投票:0回答:1

我在头文件中声明了一个模板类。

// Matrix.h
template <class X> class Matrix {};

在另一个头文件中,我有一个函数声明,该函数声明将该模板类的实例化作为返回类型:

// OtherModule.h
Matrix<double> do_stuff();

在另一个模块的源文件中,我包含 Matrix 类的标头:

// OtherModule.cpp
#include "Matrix.h"

Matrix<double> do_stuff() {
  // do stuff
}

如何让编译器知道 OtherModule 头文件中的

Matrix<double>
是什么,而不在头文件本身中包含 Matrix.h?

我尝试了向前声明,如下所示这里

// OtherModule.h
template class Matrix<double>

Matrix<double> do_stuff();

但是不起作用。

c++ templates header declaration definition
1个回答
0
投票

@n。米。可能是人工智能:你的第一条评论完成了我想做的事情。我想这样做是否真的有意义是一个单独的问题。

无论如何,使用以下代码就可以了:

// OtherModule.h:

template <class> class TMatrix;
TMatrix<double> do_stuff();
© www.soinside.com 2019 - 2024. All rights reserved.