Martin Melka
Martin Melka

Reputation: 7799

Class template using STL fails to compile

I am new to templates and am trying to compile this code:

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;
}

I have done some searching and I suspect that the problem lies with the typename keyword. However, no matter how I try, I can't find the solution.

When there is the typename, I get expected nested-name-specifier error. When it is not, I get a freakishly long STL error.

What's the catch? Thanks


EDIT: how about this scenario, where I try to store pointers to objects in STLs?

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);
};

Upvotes: 0

Views: 121

Answers (3)

user995502
user995502

Reputation:

set<const _Type & > values;

You have provided reference as an element type of set. Containers can not carry references they need pointers.

set<const _Type*> values;

Upvotes: 1

4pie0
4pie0

Reputation: 29744

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

because you cannot use reference as type in STL containers, use pointers instead:

set<const _Type*> values;

Upvotes: 1

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17434

Firstly, anything like _Foo or _Bar is not for you to use, don't copy that habit from the implementations of the standard library. Also, it doesn't make things easier to read or write.

Now, the problem in your code is that you are trying to create a set of references, but references are not valid elements for containers. A "typename" is not needed there, because no dependent type is used there.

Upvotes: 2

Related Questions