首页 > 解决方案 > 为什么重写虚函数时需要显式模板参数?

问题描述

这是我的问题。如果我没有在 derived::getType() 函数中显式放置模板参数,则会出现以下错误。

类模板参数推导仅适用于 -std=c++1z 或 -std=gnu++1z

但即使使用 -std 标志,它仍然会引发错误。

class myT {
    // full implementation
};

template<class T>
class base {
public:
    virtual my_getter_type<T>* getter() = 0;
}

class derived : public base<myT> {
public:
    my_getter_type<myT>* getter();   // this is OK, no compile error
    my_getter_type* getType();       // this is NOT OK, compile error
}

标签: c++

解决方案


你想多了。显然,返回类型必须是一个类型。my_getter_type<myT>*是一种类型。my_getter_type是一个模板。

my_getter_type*也没有意义,因为要形成指针类型,*必须遵循基类型。


推荐阅读