Friendly function of a template from several classes

I have this code:

template<typename T> T f() {
// ...
}

class A {
    friend A f();
};

class B {
    friend B f();
};

I get an error ambiguating new declaration of ‘B f()’.

However, if I change my code to the following

template<typename T> void f(T arg) {
// ...
}

class A {
    friend void f(A);
};

class B {
    friend void f(B);
};

The program compiles accurately.

Can someone help me figure out what the problem is?

+4
source share
1 answer
friend A f();

This line declares that a function without a template A f()exists and is a friend of the class. This is not the same function as f<A>()- it is a completely new function.

friend B f();

This line declares another function without a template with the same name, but has a different return type. You cannot overload the return type of a function, so this is not allowed.

, - ; , , .

, , , :

class A {
    friend A f<A>();
};

class B {
    friend B f<B>();
};

, :

class A {
    friend void f<A>(A);
};

class B {
    friend void f<B>(B);
};
+13

All Articles