Aleksey Kontsevich
Aleksey Kontsevich

Reputation: 5011

Why compiler produces an error on template function

Why following code works fine:

template <typename Set, typename Vector> void copySetToVector2(Set &s, Vector &v)
{
    copy(s.begin(), s.end(), inserter(v, v.begin()));
}

int main()
{
    set<int> s1;
    s1.insert(1);
    s1.insert(2);
    s1.insert(3);

    vector<int> v1;

    copySetToVector2(s1, v1);
    return 0;
}

But if I change variables to pointers in template function compiler produces error:

'std::set< int >*' is not a class, struct, or union type

What is wrong here?

Upvotes: 0

Views: 112

Answers (1)

Bill
Bill

Reputation: 14695

If you change this:

template <typename Set, typename Vector> void copySetToVector2(Set &s, Vector &v)

to this:

template <typename Set, typename Vector> void copySetToVector2(Set *s, Vector *v)

then the body needs to look like this:

template <typename Set, typename Vector> void copySetToVector2(Set *s, Vector *v)
{
    copy(s->begin(), s->end(), inserter(*v, v->begin()));
}

The dot notation s.begin() does not work for pointers. You need to switch to s->begin(). See This link for more details.

Upvotes: 4

Related Questions