vendredi 18 avril 2014

c ++ - méthode de la classe sub appel de fonction spécifique de la classe de base - Stack Overflow


I've got a question concerning handling of virtual function in C++ programming. I have something like this:


template<class T>
class baseClass
{
virtual void doSomething(T& t) {
// some baseClass specific code
}

void doSomethingElse(T& t) {
// some baseClass specific code

this->doSomething(t);
}
}

template<class T>
class subClass
{
virtual void doSomething(T&) {
// some subclass related code
}
}

Now, if I construct an object of type subClass....


int main(int argc, char *argv[])
{
subClass<anyType> * subClassObject = new subClass<anyType>();
subClassObject->doSomethingElse(anyTypeObject);
}

.... and call the doSomethingElse method of the base class, this method will call the doSomething method of the base class and not of the sub class.


What I want to have, is calling the doSomething method of the subclass (not of the baseClass).


Can anybody tell me how to accomplish that?




You could accomplish it with CRTP:


template<class T, class Derived>
class baseClass
{
void doSomethingElse(T& t) {
// some baseClass specific code
static_cast<Derived*>(this)->doSomething(t);
}
}

template<class T>
class subClass : public baseClass<T, subClass>
{
void doSomething(T&) {
// some subclass related code
}
}

See this for discussion about virtual template methods



I've got a question concerning handling of virtual function in C++ programming. I have something like this:


template<class T>
class baseClass
{
virtual void doSomething(T& t) {
// some baseClass specific code
}

void doSomethingElse(T& t) {
// some baseClass specific code

this->doSomething(t);
}
}

template<class T>
class subClass
{
virtual void doSomething(T&) {
// some subclass related code
}
}

Now, if I construct an object of type subClass....


int main(int argc, char *argv[])
{
subClass<anyType> * subClassObject = new subClass<anyType>();
subClassObject->doSomethingElse(anyTypeObject);
}

.... and call the doSomethingElse method of the base class, this method will call the doSomething method of the base class and not of the sub class.


What I want to have, is calling the doSomething method of the subclass (not of the baseClass).


Can anybody tell me how to accomplish that?



You could accomplish it with CRTP:


template<class T, class Derived>
class baseClass
{
void doSomethingElse(T& t) {
// some baseClass specific code
static_cast<Derived*>(this)->doSomething(t);
}
}

template<class T>
class subClass : public baseClass<T, subClass>
{
void doSomething(T&) {
// some subclass related code
}
}

See this for discussion about virtual template methods


0 commentaires:

Enregistrer un commentaire