2

我有一个模板类,它由另一个具有深层层次结构的类参数化。我想传递给另一个基类参数化的函数基模板类。这是示例:

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

我在编译期间收到此错误:

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>&)

但是,如果我使用相同的逻辑创建局部变量,它就可以正常工作:

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

2 回答 2

1

这是因为您的do_stuff函数没有模板化,并且没有简单的 from MethodImpl<U>to 转换MethodImpl<T>

更多类似的东西

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

可能有帮助。

于 2012-06-13T13:24:58.627 回答
1

类型MethodImpl<Concrete>MethodImpl<Abstract>是不同的,并且没有继承关系。MethodImpl<Abstract>和也可以这样说MethodImpl<Concrete>

该方法user::do_stuff需要 a Method<Abstract> &,因此它可以接受 a MethodImpl<Abstract>&(或任何其他派生类型的Method<Abstract>,但不能接受MethodImpl<Concrete>&.

于 2012-06-13T13:37:24.750 回答