mardi 16 février 2021

C++ template accept only typenames with certain member

I'm learning how to use templates. Let's say, I have following structure of classes. I'm using the template just for classes tC and tD(with intention of implementing more similar classes in the future). In other parts of the project I'm using only methods from the base class A for abstraction. These classes compile and run correctly in VS2019.

My questions are:

  • Is it acceptable to refer in the template class to member of the typename T? (I mean implementation of getVersion())
  • Can I specify somehow that typename T requires to have such member?
struct version {
    std::string name;
    int date;
}

class A {
    void f();
    const version& getVersion() const;
}

template <typename T>
class B : public A {
   // some methods implementation specific for class B that require using typename T

   void f() override; // implemented somewhere else
   const version& getVersion() const { return T.v; }
}

class tC {
   static constexpr version v{"tC", 1};
   // some methods for C
}

class tD {
   static constexpr version v{"tD", 2};
   // some methods for D
}

Aucun commentaire:

Enregistrer un commentaire