0

I want to make a function that takes a container T (can be vector, map, list...) as template and a T and a Int as arguments, in this function, we're assuming that T is a container of int, and I want to return the first occurence of the int in the container. Here's the function:

template <class T> int & easyfind(T container, int n)
{
    typename T<int>::iterator it;

    for (it = container.begin(); it != container.end(); it++)
        if (*it == n)
            return (*it);
    throw (NotFoundException());
}

But the compiler says "expected a qualified name after 'typename'", and when I replace the typename by class the compiler says "explicit specialization of non-template class 'T'", how can I get this to work?

3
  • 1
    You're assuming that T is a container of int, so you don't have to specify that. T<int>::iterator --> T::iterator.
    – cigien
    Jan 29, 2021 at 22:45
  • Not the answer, but () after throw are superfluous. Jan 29, 2021 at 22:46
  • thanks, i don't know why i thought it didn't work without the <int> but it works
    – Fayeure
    Jan 29, 2021 at 22:48

1 Answer 1

2

T is a type, not a template. You need

typename T::iterator it;

to access its iterator type member.

The reason you see code like

std::vector<int>::iterator

is because std::vector is the name of a template, and you need to specify the template parameter. In your case T is already an instantiation of a template, so there is no need to specify the parameter.

3
  • thanks, it works, I thought I tested this but I didn't :)
    – Fayeure
    Jan 29, 2021 at 22:50
  • Now it says I can't compare *it with n? why ? isnt operator * returning a reference ?
    – Fayeure
    Jan 29, 2021 at 22:55
  • 1
    @Fayeure It depends on the container. If you are using a vector, then it should work. If you are using a map then *it is a std::pair<const key, value>. Jan 29, 2021 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.