引用模板化类/对象的数据成员

chr*_*244 2 c++ templates c++11 c++14

如何在不同的模板化对象中放置对模板化对象的引用(模板化,虽然我不确定是否相关)类?

目前我有(简化):

template <typename T, size_t D>
class Field
{
public:
    template <size_t meshDim>
    Field(const Mesh<meshDim>& mesh, const std::string &fileName):
    fileName_(fileName),
    meshDim_(meshDim),
    mesh_(mesh) // <- this also doesn't compile, 
                // although I think it would if I had a data member named 
                // mesh_ that compiled
    {
        for (unsigned int d=0; d<D; d++) {
            field_[d].reserve(mesh.numCells());
        }
    }

private:
    std::vector<T> field_[D];
    std::string fileName_;
    const size_t meshDim_;
    template<size_t meshDim>
    const Mesh<meshDim> &mesh_; // <- This doesn't compile
};
Run Code Online (Sandbox Code Playgroud)

这会遇到编译时错误:data member 'mesh_' cannot be a member template.关于变量模板的这个链接让我想到我正在尝试做什么(或者至少,类似于我正在尝试做的事情)应该是可能的c++14,但可能不是c++11.

如果我删除template<size_t meshDim>行之前的const Mesh<meshDim> &mesh_;行(也删除模板参数,以避免未定义meshDim),那么我被告知我正在制作invalid use of template-name 'Mesh' without an argument list,这是有道理的.

如果我离开<>,但没有争论(不是我希望这可以工作,但尝试任何事情),我得到wrong number of template arguments (0, should be 1).

这可能吗?我需要做的一些部分/全部零件/所有的东西(一个或多个)static或者是constexpr

原则上,应该只有一个Mesh对象,并且我可以尝试使其成为constexpr构造函数,因为它需要的参数可以#define由构建系统(如果需要).

Dan*_*our 5

在您当前的代码中,您的字段类行为明确依赖于meshDim.至少那是你的代码所说的.因此,您需要在网格维度上对其进行参数化:

template< typename T, size_t D, size_t meshDim>
class Field {
  // ...
  Field(mesh<meshDim> & m);
  // ...
  mesh<meshDim> & mesh_;
};
Run Code Online (Sandbox Code Playgroud)

如果field的行为不是直接取决于网格大小,例如它可以采用任何网格,那么你需要给它一个不依赖于网格大小的类的引用:

class IMesh {
  virtual void doStuff(void) = 0; // your interface
  // ...
};
template<size_t meshDim>
class Mesh : public IMesh { // vtable or similar means required now
  // ...
};

template< typename T, size_t D>
class Field {
  // ...
  Field(IMesh &);
  // ...
  IMesh & mesh_; // Reference, so no slicing
};
Run Code Online (Sandbox Code Playgroud)

关于变量模板:它们不能解决您的问题:

在类作用域中使用时,变量模板声明静态数据成员模板. (资源)

...这是有道理的,因为如果你可以为非静态数据成员提供变量模板,就不可能在它的声明中计算对象的大小,因为那时你无法知道将要进行什么样的实例化.