c++ - 类模板中的虚函数

标签 c++ templates

我有一个名为 Cache 的模板类,它是字符串和对象的 std::map 的容器。

template<class T>
class Cache
{
public:
    Cache() {}
    virtual ~Cache();

    virtual T* loadObject(const char *file);
    virtual bool removeObject(const char *file);
    virtual void removeAllObjects();

    virtual unsigned int getNumObjects() const;
    virtual T* getObject(const char *file);

protected:
    typedef std::shared_ptr<T> t_ptr;

    std::unordered_map<std::string, t_ptr> _objects; //file, shared ptr of object
};

template<class T>
T* Cache<T>::loadObject(const char *file)
{
    //if object exists
    T *obj = getObject(file);
    if(obj)
        return obj;

    obj = new T();

    if(obj)
        return _objects.insert(std::make_pair(file,t_ptr(obj))).first->second.get();
    else
        return nullptr;
}

还有一个继承自 Cache 的模板类称为 ResourceCalled,它基本上是同一个类,但具有不同的 loadObject() 方法。

template<class T>
class ResourceCache : public Cache<T>
{
public:
    ResourceCache(ResourceLoader<T> *resourceLoader) : _resourceLoader(resourceLoader)
    {}

    virtual T* loadObject(const char *file);

private:
    ResourceLoader<T> *_resourceLoader;
};

template<class T>
T* ResourceCache<T>::loadObject(const char *file)
{
    //if object exists
    T *obj = getObject(file);
    if(obj)
        return obj;

    obj = _resourceLoader->load(file);
    if(obj)
        return _objects.insert(std::make_pair(file,t_ptr(obj))).first->second.get();
    else
        return nullptr;
}

在我的程序中,我启动 ResourceCache<> 并将 T 设置为一个名为 Mesh 的类,该类在其构造函数中有一个参数。现在,当我尝试编译我的程序时,编译器会提示:

error C2512: 'Mesh' : no appropriate default constructor available

这就像它正在尝试为 Cache 而不是 ResourceCache 构建代码。但是当我在 Cache::loadObject() 之前省略 virtual 关键字时,程序可以编译。

为什么会这样?我学会了在继承时总是使用 virtual 关键字。

最佳答案

Cache<T>::loadObject() , 你有这条线

obj = new T();

如果T,该行不起作用, Mesh在您的情况下,没有默认构造函数。

Cache<T>::loadObject()virtual ,函数的基类实现和派生类实现都被实例化。

Cache<T>::loadObject()不是 virtual ,只有函数的派生类实现被实例化。函数的基类实现只有在显式使用时才会被实例化。

关于c++ - 类模板中的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908580/

相关文章:

c++ - 如何限制模板仿函数返回和参数类型

c++ - 有没有一种聪明的方法来禁止派生类之一隐藏基类的运算符函数

c++ - 链接来自 2 个不同 MFC 控件的滚动条

c++ - 我自己的连接函数不会更改目标字符串

c++ - 我可以使用类型特征从 C++ 中的枚举值推断出枚举的类型吗?

c++ - 作为仿函数模板的模板参数

javascript - 模板中的 Bigcommerce 购物车内容

c++ - 在 C++ 中比较 bool 和 1

c++ - 如何获取使用 malloc() 分配的内存块的大小?

c++ - 为 Boost Fusion 调整一个空结构