首页 文章

错误在模板中返回std :: set <T> :: iterator

提问于
浏览
5

我正在围绕std :: set创建一个模板包装器 . 为什么我的Begin()函数声明会出错?

template <class T>
class CSafeSet
{
    public:
        CSafeSet();
        ~CSafeSet();

        std::set<T>::iterator Begin();

    private:
        std::set<T> _Set;
};

错误:类型'std :: set,std :: allocator <_CharT >>'不是从'CSafeSet'类型派生的

1 回答

  • 17

    试试typename

    template <class T>
    class CSafeSet
    {
        public:
            CSafeSet();
            ~CSafeSet();
    
            typename std::set<T>::iterator Begin();
    
        private:
            std::set<T> _Set;
    };
    

    您需要typename,因为它依赖于模板T.代码上方链接中的更多信息 . 如果你使用typedef,很多东西都会变得容易:

    template <class T>
    class CSafeSet
    {
        public:
            typedef T value_type;
            typedef std::set<value_type> container_type;
            typedef typename container_type::iterator iterator_type;
            typedef typename container_type::const_iterator const_iterator_type;
    
            CSafeSet();
            ~CSafeSet();
    
            iterator_type Begin();
    
        private:
            container_type _Set;
    };
    

    另外,如果您想要完成,您需要允许CSafeSet执行与set could相同的操作,这意味着使用自定义比较器和分配器:

    template <class T, class Compare = std::less<T>, class Allocator = std::allocator<T> >
    class CSafeSet
    {
        public:
            typedef T value_type;
            typedef Compare compare_type;
            typedef Allocator allocator_type;
    
            typedef std::set<value_type, compare_type, allocator_type> container_type;
            typedef typename container_type::iterator iterator_type;
            typedef typename container_type::const_iterator const_iterator_type;
    
            // ...
    }
    

    最后一点建议,如果要创建一个类的包装器,请尝试遵循与类来源相同的命名约定 . 也就是说,你的 Begin() 应该是 begin() (而且我个人认为在类名之前的C很奇怪,但那个由你决定:])

相关问题