【问题标题】:Class template using STL fails to compile使用 STL 的类模板无法编译
【发布时间】:2013-04-06 11:57:06
【问题描述】:

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

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 关键字上。但是,无论我如何尝试,我都找不到解决方案。

当有类型名时,我得到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);
};

【问题讨论】:

标签: c++ templates stl


【解决方案1】:

首先,像 _Foo 或 _Bar 这样的东西不适合你使用,不要从标准库的实现中复制这个习惯。此外,它不会让事情变得更容易阅读或写作。

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

【讨论】:

    【解决方案2】:
    set<const _Type & > values;
    

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

    set<const _Type*> values;
    

    【讨论】:

    • @MartinMelka Needle 是一个模板类。所以在使用时需要一个模板类型。 set&lt;const Needle&lt;_Type&gt;*&gt; values;
    【解决方案3】:
    /*typename(?)*/ set<const _Type & > values; // problem
                                   ^^^
    

    因为您不能在 STL 容器中使用引用作为类型,所以请改用指针:

    set<const _Type*> values;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多