mardi 21 juillet 2015

Data member referencing templated class/object

How can I place a reference to a templated class object inside a different (templated, although I'm not sure that's relevant) class?

Currently I have (simplified):

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
};

This hits a compile-time error: data member 'mesh_' cannot be a member template. This link about variable templates makes me think what I'm trying to do (or at least, something similar to what I'm trying to do) should be possible with c++14, but probably not with c++11.

If I remove the template<size_t meshDim> line before the const Mesh<meshDim> &mesh_; line (removing the template arguments also, to avoid undefined meshDim), then I'm told that that I'm making invalid use of template-name 'Mesh' without an argument list, which makes sense.

If I leave in the <>, but without an argument (not that I expected this to work, but trying anything), I get wrong number of template arguments (0, should be 1).

Is this possible? Do I need to make some/all parts of some/all thing(s) static or perhaps constexpr?

In principle, there should be only one Mesh object, and I'm ok with trying to make it a constexpr constructor, since the parameters it needs could be #defined by the build-system, if needed.

Aucun commentaire:

Enregistrer un commentaire