Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot understand friend functions in a template class

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);
};
like image 761
asheeshr Avatar asked Nov 19 '12 10:11

asheeshr


People also ask

Can a template class be a friend?

Many-to-one: All instantiations of a template function may be friends to a regular non-template class. One-to-one: A template function instantiated with one set of template arguments may be a friend to one template class instantiated with the same set of template arguments.

How do you call a function in a template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Can we define friend function inside the class?

Friend functions can be defined (given a function body) inside class declarations. These functions are inline functions. Like member inline functions, they behave as though they were defined immediately after all class members have been seen, but before the class scope is closed (at the end of the class declaration).

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.


1 Answers

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().

like image 183
Angew is no longer proud of SO Avatar answered Sep 18 '22 08:09

Angew is no longer proud of SO