c++ - 将模板类的对象作为需要基模板类的函数参数传递

标签 c++ templates generic-programming

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

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

最佳答案

那是因为你的do_stuff函数未模板化,并且没有来自 MethodImpl<U> 的简单转换至 MethodImpl<T> .

更多的是

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

可能会有帮助。

关于c++ - 将模板类的对象作为需要基模板类的函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11015670/

相关文章:

c++ - 使用 Xcode 的综合工具包

c++ - 基于模板参数的条件编译时包含/排除代码?

java - 使用 Spring Boot Data JPA 按需创建表

rust - 特性作为通用参数来构造对象初始化

C++ boost 线程在 MFC 中锁定 GUI 线程

c++ - 编译器是否使用 C 预处理器输出中的行标记?

c++ - 模板类的转换

html - 使用 HTML::Template 的控制逻辑

sql - 使用GoLang包“database/sql”时,是否可以使用通用类型变量检索查询结果

c++ - glibc 检测到双重释放或损坏