使用STL的类模板无法编译

时间:2013-04-06 11:57:07

标签: c++ templates stl

我是模板的新手,我正在尝试编译此代码:

template <typename _Type, typename _Comparator = std::equal_to<_Type> >
    class CSearch {
public:
    CSearch() : cmp(_Comparator()) {
    }

    CSearch(const _Comparator &_cmp) : cmp(_cmp) {
    }

    void Add(int id,
            const _Type & needle) {
        values.insert(needle); // problem
    }

    set<int> Search(const _Type & hayHeap) const {

    }
private:
    const _Comparator &cmp;

    /*typename(?)*/ set<const _Type&> values; // problem

    CSearch(const CSearch &other);
    CSearch &operator=(const CSearch &other);
};

(...)

int main(){
    CSearch <string> test;
}

我做了一些搜索,我怀疑问题出在typename关键字上。但是,无论我如何尝试,我找不到解决方案。

如果有typename,我会收到expected nested-name-specifier错误。如果不是,我会得到一个非常长的STL错误。

有什么收获?感谢


编辑:这个场景怎么样,我试图在STL中存储指向对象的指针?

template <typename _Type>
class Needle {
public:
    int ID;
    _Type *data;
};

template <typename _Type, typename _Comparator = std::equal_to<_Type> >
        class CSearch {
public:

    CSearch() : cmp(_Comparator()) {
    }

    CSearch(const _Comparator &_cmp) : cmp(_cmp) {

    }

    void Add(int id,
            const _Type & needle) {
        Needle<_Type> *tmp = new Needle<_Type>();
        tmp -> ID = id;
        tmp -> data = &needle;
        values.insert(tmp);
    }

    set<int> Search(const _Type & hayHeap) const {

    }
private:
    const _Comparator &cmp;

    set<const Needle*> values;

    CSearch(const CSearch &other);
    CSearch &operator=(const CSearch &other);
};

3 个答案:

答案 0 :(得分:2)

首先,像_Foo或_Bar这样的东西不适合你使用,不要从标准库的实现中复制这种习惯。此外,它不会使读取或写入更容易。

现在,您的代码中的问题是您正在尝试创建一组引用,但引用不是容器的有效元素。那里不需要“typename”,因为那里没有使用依赖类型。

答案 1 :(得分:1)

set<const _Type & > values;

您提供了参考作为集合的元素类型。容器不能携带他们需要指针的引用。

set<const _Type*> values;

答案 2 :(得分:1)

/*typename(?)*/ set<const _Type & > values; // problem
                               ^^^

因为你不能在STL容器中使用reference作为类型,而是使用指针:

set<const _Type*> values;