Validus Oculus
Validus Oculus

Reputation: 2711

Unresolved template argument

i was testing some template codes today and, i find out something interesting but I could not find any good reason to explain why does it happen. I request to you consider and enlighten me with your knowledge. Thanks for your time.

This code block is working without problem.

template<class TItem>
class PrintableQueue : public queue<TItem> {
    public:
        friend ostream& operator<<(ostream& os, const PrintableQueue<TItem>& queue) {
            copy(queue.c.begin(), queue.c.end(), ostream_iterator<TItem>(os, " "));
            return os;
        }
};
int main(int argc, const char* argv[])
    PrintableQueue<int> queue;
    queue.push(1);
    queue.push(2);

    cout << queue;
}

However, when i put the definition of friend function to the outside of the class, it does not work.

template<class TItem>
class PrintableQueue : public queue<TItem> {
    public:
        friend ostream& operator<<(ostream& os, const PrintableQueue<TItem>& queue);
};
ostream& operator<<(ostream& os, const PrintableQueue<TItem>& queue) {
    copy(queue.c.begin(), queue.c.end(), ostream_iterator<TItem>(os, " "));
    return os;
}

The errors i got is below.

'TItem' : undeclared identifier
'PrintableQueue' : 'TItem' is not a valid template type argument for parameter 'TItem'

My question is, why compiler can not resolve TItem ?

Upvotes: 1

Views: 91

Answers (2)

R Sahu
R Sahu

Reputation: 206717

You need to make the function a function template.

First change the decleration of the operator<< in the class and include TItem into its signature

friend ostream& operator<< <TItem>(ostream& os, const PrintableQueue<TItem>& queue);

Than change your function definition to template function

template <typename TItem>
ostream& operator<<(ostream& os, const PrintableQueue<TItem>& queue) {
    copy(queue.c.begin(), queue.c.end(), ostream_iterator<TItem>(os, " "));
    return os;
}

Upvotes: 1

vsoftco
vsoftco

Reputation: 56577

It doesn't know what TItem is, it is now moved outside the class template.

Upvotes: 0

Related Questions