C++ - 恢复模板或转换为模板

标签 c++ templates c++11

考虑以下代码 list :

#include <iostream>
#include <typeinfo>

class Interface { };

template<typename T>
class Class : public Interface { };

template<typename T>
Interface *producer() {
    std::cout << "produced " << typeid(T).name();
    return new Class<T>();
}

template<typename T>
void consumer(Class<T> *class_value) {
    std::cout << "consumed " << typeid(T).name();
}

void mediator(Interface *value) {
    /* The magic happens here */
    consumer(class_value);
}

int main() {
    Interface *value = producer<int>();
    mediator(value);
}

是否有任何可能的方法从“中介”函数调用“消费者”模板函数?

最佳答案

如果稍微改变一下设计,就可以让派生类来完成这项工作:

class Interface
{
    virtual void consume() = 0;
    virtual ~Interface() {}
};

void mediator(Interface * value)
{
    value->consume();
}

template <typename T>
void consumer(Class<T> * class_value)
{
    std::cout << "consumed " << typeid(T).name();
}

template <typename T> class Class : public Interface
{
    virtual void consume() override
    { 
        consumer<Class>(this);
    }
    // ...
};

关于C++ - 恢复模板或转换为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538637/

相关文章:

c++ - C++文件读写

c++ - 具有未定义成员函数返回类型的模板实例化

c++ - 为什么以不同的顺序使用 std::remove_reference 和 std::remove_const 会产生不同的结果?

c++ - Boost ASIO async_read 不从客户端读取数据

python - 如何使用 boost::python 将模板化类作为一个类公开给 python

c++ - boost 可以有带整数键的 map 吗?

swift - 在 Swift 中使用模板键入别名声明

c++ - 如何在 C++ 函数模板中指定默认的非模板参数初始值设定项?

c++ - 将函数作为参数传递给模板返回值

c++ - 如何使用 Alchemy 将 C++ 移植到 swf?