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);
};
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.
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.
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).
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With