c++ - 在函数中返回 "template class object"

标签 c++ function templates

我有一个这样的模板类

//Matrix.h
template <class T = double>
class Matrix
{
    //some constructors variables and ...
};

在名为 Matrix.h 的文件中定义,现在我如何从其他文件中的此类返回对象,例如 assemble.h 类似:

//assemble.h
#include "Matrix.h"
Matrix<T> assemble(Matrix<T> KG,int node)
{
    //some other codes
}

最佳答案

[Matrix template] defined in a file called Matrix.h now how can I return an object from this class in other file say assemble.h

Matrix本身不是一个类。这是一个模板;将其视为创建类的一种方式,例如Matrix<int> , Matrix<std::string> , Matrix<double>Matrix<MyClass> .

因此,问题是:你想要你的assemble吗?函数与任何矩阵类一起工作,还是您希望它与一个特定矩阵类一起工作?

在前一种情况下,您还必须将函数模板化(这意味着,与上面发生的情况类似,您不再拥有函数,而是拥有函数创建机制):

template <class ContentType>
Matrix<ContentType> assemble(Matrix<ContentType> KG, int node)
{
    // ...
}

(在此示例中,我将模板参数命名为 ContentType,这样您就可以看到它不必与 Matrix 中的模板参数同名。)

在后一种情况下,您必须指定具体类:

Matrix<int> assemble(Matrix<int> KG, int node)
{
    // ...
}

顺便说一句,您可能希望通过常量引用传递矩阵对象,尤其是在缺少 C++11 移动功能的情况下。

关于c++ - 在函数中返回 "template class object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337491/

相关文章:

c++ - 使用并行编程时调用函数

c++ - 使用路径中的空格从 C++ 执行批处理文件

ios - 如何为 Xcode 自定义 ViewController 模板文件?

c++ - 在 MSVC C++ DLL 中导出模板化类的模板化成员函数

templates - Pandoc 用户数据目录

c++ - 如何在 std::thread 中正确嵌入 QEventLoop?

c++ - 如何连接矩阵?

c - 从不改变表达式中的状态

Python:缩进错误

javascript - HTML javascript 函数