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

jac*_*hab 5 c++ templates stl

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

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

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

    private:
        std::set<T> _Set;
};
Run Code Online (Sandbox Code Playgroud)

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

GMa*_*ckG 17

尝试typename:

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

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

    private:
        std::set<T> _Set;
};
Run Code Online (Sandbox Code Playgroud)

您需要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;
};
Run Code Online (Sandbox Code Playgroud)

另外,如果您想要完成,您需要允许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;

        // ...
}
Run Code Online (Sandbox Code Playgroud)

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