简体   繁体   English

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

[英]error returning std::set<T>::iterator in template

I'm making a template wrapper around std::set. 我正在围绕std :: set创建一个模板包装器。 Why do I get error for Begin() function declaration? 为什么我的Begin()函数声明会出错?

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

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

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

error: type 'std::set, std::allocator<_CharT> >' is not derived from type 'CSafeSet' 错误:类型'std :: set,std :: allocator <_CharT >>'不是从'CSafeSet'类型派生的

Try typename : 尝试typename

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

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

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

You need typename there because it is dependent on the template T. More information in the link above the code. 您需要typename,因为它依赖于模板T.代码上方链接中的更多信息。 Lot's of this stuff is made easier if you use typedef's: 如果你使用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;
};

On a side note, if you want to be complete you need to allow CSafeSet to do the same thing as a set could , which means using a custom comparer and allocator: 另外,如果您想要完成,您需要允许CSafeSet执行与set相同的操作,这意味着使用自定义比较器和分配器:

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;

        // ...
}

And a last bit of advice, if you are going to create a wrapper around a class, try to follow the same naming conventions as where the class came from. 最后一点建议,如果要创建一个类的包装器,请尝试遵循与类来源相同的命名约定。 That is, your Begin() should probably be begin() (And personally I think C before a class name is strange but that one is up to you :]) 也就是说,你的Begin()应该是begin() (而且我个人认为C类在一个类名之前是奇怪的但是那个由你决定:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM