c++ - 为什么来自模板化基类的方法不可见?

标签 c++ templates

我有一个提供方法 remove() 的模板化基类。我有一个派生自不隐藏 remove() 方法的模板化基类的类。但是,基于模板的类的 remove 方法是不可见的。为什么?有没有办法解决这个问题(我的意思是除了我最后想出的“技巧”之外)?

我已将其简化为一个小代码示例:


#include <map>
#include <iostream>
#include <boost/shared_ptr.hpp>



// Common cache base class. All our caches use a map, expect children to
// specify their own add, remove and modify methods, but the base supplies a
// single commont remove too.
template <class T>
class cache_base {
public:

    cache_base () {};

    virtual ~cache_base() {};

    virtual void add(uint32_t    id) = 0;

    virtual void remove(uint32_t    id) = 0;

    void remove() {
        std::cout << "This is base remove\n";
    };

    virtual void modify(uint32_t    id) = 0;

protected:
    typedef std::map< uint32_t, typename T::SHARED_PTR_T>    DB_MAP_T;

    DB_MAP_T    m_map;
};


// A dummy item to be managed by the cache.
class dummy {
public:
    typedef    boost::shared_ptr<dummy>    SHARED_PTR_T;

    dummy () {};
    ~dummy () {};
};


// A dummy cache
class dummy_cache :
    public cache_base<dummy>
{
public:
    dummy_cache () {};

    virtual ~dummy_cache () {};

    virtual void add(uint32_t    id) {};

    virtual void remove(uint32_t    id) {};

    virtual void modify(uint32_t    id) {};
};




int
main ()
{
    dummy_cache    D;

    D.remove();

    return(0);
}

此代码编译失败,出现以下错误


g++ -g -c -MD -Wall -Werror -I /views/LU-7.0-DRHA-DYNAMIC/server/CommonLib/lib/../include/ typedef.cxx
typedef.cxx: In function 'int main()':
typedef.cxx:67: error: no matching function for call to 'dummy_cache::remove()'
typedef.cxx:54: note: candidates are: virtual void dummy_cache::remove(uint32_t)
make: *** [typedef.o] Error 1

我不知道它是否有所不同,但我使用的是 g++ 版本 4.1.2 20070115。

此外,我发现如果我将以下删除方法添加到 dummy_cache 它会起作用。但是,我必须在 dummy_cache 中添加一个从属方法来公开一个公共(public)基方法,这让我感觉很奇怪。

void remove () {return cache_base<dummy>::remove(); }

最佳答案

您的重载 dummy_cache::remove(uint32_t) 隐藏了 cache_base::remove()。您可以取消隐藏:

class dummy_cache :
    public cache_base<dummy>
{
public:
  using cache_base<dummy>::remove;
  ...
};

关于c++ - 为什么来自模板化基类的方法不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10215989/

相关文章:

c++ - 在 C++ unordered_map 中有效地使用 [] 运算符

c++ - 具有可变参数的映射函数并通过字符串调用 c++

c++链表模板和节点

C++使用ifstream读取文件

C++ : In how many ways compiler optimizes away our code?

c++ - malloc 和 free 是如何实现的?

c++ - enable_if_t 中包含折叠表达式的编译器错误

c++ - 可变参数模板 lambda 参数的模板推导

c++ - 模板调用有什么区别?

c++ - QList 模板化结构