6

This is code i have written to understand the concept. The code is fine and it runs.

What i dont understand is that why is the marked line needed ?

template <class T>
class D
{
    public :
    template <class P>  //<------------------Why is this needed ? --------------
    friend void print(D <P> obj);
};

template <class T>
void print(D<T> obj)
{std::cout<<sizeof(T);};


int main()
{
    D <char>obj3;
    print(obj3);
    return 0;
}

or in other words why does the following not run ?

template <class T>
class D
{
    public :
    friend void print(D <T> obj);
};
asheeshr
  • 4,088
  • 6
  • 31
  • 50
  • That line shows that `print()` is itself a `template` function. – iammilind Nov 19 '12 at 10:27
  • Why is that needed in the class ? The template function has a complete definition outside the class, plus instantiation is done with knowledge of the data type .. – asheeshr Nov 19 '12 at 10:34
  • As per the syntax of template function before declaring template function you must write it like this... `template friend void print(D

    obj);` I think that must be a reason.

    – Heena Hussain Nov 19 '12 at 11:13

1 Answers1

9

As per [temp.friend], you must provide explicit template arguments to make a specialisation of a template function a friend:

template <class T>
class D
{
    public :
    friend void print<T>(D <T> obj);
};

Without it, the compiler will be looking for a function print(), not a function template print().

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Could you explain what are explicit template arguments ? Cant really get a hang of it from the sites that google is turning up .. – asheeshr Nov 19 '12 at 12:34
  • 1
    @AshRj I'll explain on calls as there it's easiest, but it applies to all times you're referring to a function template. Let's assume you have an instance defined `D d;`. When calling `print()`, you can either provide the tempalte arguments explicitly: `print(d);`, or do not provide them and let the compiler deduce them from the context (here, from the argument): `print(d);`. Providing them explicitly means listing them in angle brackets `< >`. – Angew is no longer proud of SO Nov 19 '12 at 12:39
  • Thanks for the explanation. I got what you are saying but i still cant get how that explains your answer .. Could you direct me to anyplace where i can read about how templates work ? I think the main issue here is that i dont understand how templates are handled by the compiler, hence, the difficulty in understanding something so simple .. – asheeshr Nov 19 '12 at 12:48
  • @AshRj In my answer, the explicit argument is the `` in `print(`. I don't know a reference I could suggest, but there's a list of [books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) here on SO, perhaps you can work your way from there. [temp.friend] in my answer is a reference to the C++11 ISO standard. – Angew is no longer proud of SO Nov 19 '12 at 12:54