【问题标题】:C++ function that accepts parametrized type including subtypes接受参数化类型(包括子类型)的 C++ 函数
【发布时间】:2014-12-16 21:10:39
【问题描述】:

OpenFOAM 库定义了两种类型,volMeshsurfaceMesh,它们都继承自GeoMesh<fvMesh>。我想定义一个接受参数的函数:

void foo(GeometricField<vector, fvsPatchField, GeoMesh<fvMesh> >& field) { ... }

但是,当我尝试调用该函数时,g++ 会给出错误“引用类型的初始化无效”:

// surfaceVectorField is a typedef GeometricField<vector, fvsPatchField, surfaceMesh>
surfaceVectorField Uf( /* initialisation arguments */ ); 
foo(Uf);

来自Java背景,这个问题似乎类似于忘记使用诸如

之类的声明
void foo(GeometricField<vector, fvsPatchField, ? extends GeoMesh<fvMesh>> field) { ... }

如果可能,我需要避免使用 C++11 特有的功能。

【问题讨论】:

  • 你能多加一点代码吗,例如你如何尝试调用你的函数?
  • 是函数调用foo()的错误还是Uf的变量定义错误? stackoverflow.com/questions/9285627/…
  • 可能它无法将您的surfaceMesh参数转换为GeoMesh&lt;fvMesh&gt;,或者整个构造都无法转换为对正确复杂类型的引用。
  • @RichardChambers:错误来自对foo()的调用
  • 在初始化surfaceVectorField时尝试将surfaceMesh显式转换为GeoMesh&lt;fvMesh&gt;

标签: c++ templates openfoam


【解决方案1】:

您的函数声明中的基本问题是无法解析参数的类型。也就是说,如果将基类作为模板参数,就无法推断出模板类的具体化。

您希望采用的参数是模板类 GeometricField 的一个实例。此外,类模板的名称不是类型。表示无法定义函数foo(GeometricField&amp; field);

如果您希望函数接受来自表面和体积网格类型的几何场,您需要将其设为模板函数或重载它。第一个模板:

template <typename T>
void foo(GeometricField<vector, fvsPatchField, T>& field) {}

或者只是

template <typename T>
void foo(T& field) {}

哪个更适合您在函数中所做的事情。另请注意,如果要重用该函数,则需要注意参数不是您期望的情况。

重载:

void foo(surfaceVectorField& field);
void foo(volVectorField& field);

这两种解决方案都可以帮助您实现目标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多