【问题标题】:C++ Making a container-like classC++ 制作类似容器的类
【发布时间】:2013-12-17 17:25:54
【问题描述】:

我正在尝试创建一个应该定义图形搜索算法行为的类。

该类接收一个通用容器作为模板参数并根据该容器进行操作

template <typename N, typename E, class Container>
class Frontier {
    private:
        Container frontier;

    public:
        bool isEmpty() { return this.frontier.empty(); }

        typename Graph<N, E>::const_iterator pop() { return this.frontier.pop(); }

        bool push(typename Graph<N, E>::const_iterator it) { return this.frontier.push(it); }
};

但是当我尝试编译时,我得到了

request for member ‘frontier’ in ‘this’, which is of non-class type 

我知道这是可以做到的,因为 stl 容器就是这样实现的

template<class T, Class C = deque<T> > class std::stack;

我注意到 Class 中的大写 C,所以我尝试在实现中使用 Class,但我从编译器得到“未定义类”。我该如何解决这个问题?

【问题讨论】:

    标签: c++ templates containers


    【解决方案1】:

    您错过了错误消息的结尾,它会告诉您this 是一个指针,并询问您是否打算使用-&gt; 而不是.。这应该可以解决错误。

    请注意,classtypename 在模板参数列表中是等价的。没什么大不了的,但一致性很好。 (请注意,Class 作为关键字无效。不知道你从哪里得到的......)

    template <typename N, typename E, typename Container>
    class Frontier {
        private:
            Container frontier;
    
        public:
            bool isEmpty() { return this->frontier.empty(); }
    
            typename Graph<N, E>::const_iterator pop() { return this->frontier.pop(); }
    
            bool push(typename Graph<N, E>::const_iterator it) { return this->frontier.push(it); }
    };
    

    【讨论】:

    • 不敢相信我错过了。我应该更新那个讨厌的编译器,这样它才能正确显示错误消息(这实际上是整个错误消息,而且我的 gcc 版本真的很旧。)
    猜你喜欢
    • 2011-04-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多