Connecting Tech Pros Worldwide Forums | Help | Site Map

Template Friend Function

Dmitry D
Guest
 
Posts: n/a
#1: Jul 19 '05
Hi all,
I'm having problems with declaring a template friend function. It seems like
I've done everything as explained
in C++ FAQ, but still, I'm getting the linker error (unresolved external
'aFunc(A<char> const&)' ) in
the following sample program. Tried it on GCC and Borland's compiler.
Can somebody please show me the correct way to fix this?

Thanks,
Dmitry

// all the following code is located in a single source file
#include <iostream>
template<typename T> class A; // forward class declaration
template<typename T> void aFunc(const A<T>&);

template <typename T>
class A
{
public:
A(T _object): value(1), object(_object) {}
T& GetObject() { return object; }

friend void aFunc(const A<T>&);
private:
T object;
int value;
};

// friend function
template <typename T>
void aFunc(const A<T>& container)
{
std::cout << "value: " << container.value;
}

int main()
{
A<char> myClass('a');
aFunc(myClass);
return 0;
}



Oplec
Guest
 
Posts: n/a
#2: Jul 19 '05

re: Template Friend Function


Dmitry D wrote:[color=blue]
> Hi all,
> I'm having problems with declaring a template friend function. It seems like
> I've done everything as explained
> in C++ FAQ, but still, I'm getting the linker error (unresolved external
> 'aFunc(A<char> const&)' ) in
> the following sample program. Tried it on GCC and Borland's compiler.
> Can somebody please show me the correct way to fix this?
>
> Thanks,
> Dmitry
>
> // all the following code is located in a single source file
> #include <iostream>
> template<typename T> class A; // forward class declaration
> template<typename T> void aFunc(const A<T>&);
>
> template <typename T>
> class A
> {
> public:
> A(T _object): value(1), object(_object) {}
> T& GetObject() { return object; }
>
> friend void aFunc(const A<T>&);
> private:
> T object;
> int value;
> };
>
> // friend function
> template <typename T>
> void aFunc(const A<T>& container)
> {
> std::cout << "value: " << container.value;
> }
>
> int main()
> {
> A<char> myClass('a');
> aFunc(myClass);
> return 0;
> }
>
>[/color]

Hi, I asked this question a few days ago. I was trying it the way you
were too. The following is what I learned on declaring friends in
templates: You need to add <> in the declaration, but not in the definition.

- Declaring a class template to be a friend takes the form:
template<class ...> friend class ...;

- Declaring an operator to be a friend takes the form:
friend ... operator... <>(...);


I have not tried to declare a regular function to be a friend, but I
assume you should use "friend void aFunc<>(const A<T>&);"

Since aFunc is a template, you have to tell the compiler that it is in
the declaration. You might try "template<class T> friend void
aFunc()(const A<T>&);"

I'm new to this too, and hope that I've been of help.

Closed Thread