Search code examples
c++templatesgeneric-programming

Passing object of a template class as a function parameter which expects base template class


I have a template class which parametrized by another class with deep hierarchy. I want to pass to a function base template class parametrized by another base class. Here is the example:

// Base template class test
#include <stdio.h>

// Base classes
template<class T>
class Method {
public:
    Method<T> (T * t) {
        this->t = t;
    }

    virtual int solve() = 0;

protected:
    T * t;
};

class Abstract {
public:
    virtual int get() = 0;
    virtual void set(int a) = 0;
};

// Concrete classes, there might be a few of them
template<class T>
class MethodImpl : public Method<T> {
public:
    MethodImpl<T> (T * t) : Method<T>(t) {}

    int solve() {
        return this->t->get() + 1;
    }
};

class Concrete : public Abstract {
public:
    int get() {
        return this->a;
    }
    void set(int a) {
        this->a = a;
    }
protected:
    int a;
};

// Uses methods of Base classes only
class User {
public:
    int do_stuff(Abstract & a, Method<Abstract> & ma) {
        a.set(2);
        return ma.solve();
    }
};

// Example usage
int main () {
    Concrete * c = new Concrete();
    MethodImpl<Concrete> * mc = new MethodImpl<Concrete>(c);

    User * u = new User();
    int result = u->do_stuff(*c, *mc);
    printf("%i", result);

    return 0;
}

I get this error during compilation:

btc.cpp: In function 'int main()':
btc.cpp:62: error: no matching function for call to 'User::do_stuff(Concrete&, MethodImpl<Concrete>&)'
btc.cpp:50: note: candidates are: int User::do_stuff(Abstract&, Method<Abstract>&)

However it works fine if I create local variables with the same logic:

int main () {
    Abstract * a = new Concrete();
    Method<Abstract> * ma = new MethodImpl<Abstract>(a);

    a->set(2);
    int result = ma->solve();
    printf("%i", result);

    return 0;
}

Solution

  • It is because your do_stuff function is not templated, and there's no simple cast from MethodImpl<U> to MethodImpl<T>.

    Something more along the lines of

    template<class T>
    int do_stuff(T& t, Method<T> & mt) {
        ...
    }
    

    might help.