简体   繁体   中英

A trouble in definition a friend function of template class in the namespace in c++

namespace N
{
    template<typename tname> class C
    {
    public:
            friend void f(int, C<tname>);
    };
}

template<typename tname>
    void N::f(int, N::C<tname>)
    {   
    }

I am creating a friend function f like above but the compiler informed me this error :

'f': is not a member of N.

Meanwhile, without the namespace, my code will run correcly.

My code will be correct too when I use normal class instead of generic class (no remove namespace).

And it will also have no error with fully declaration. Like following code:

namespace N
{
    template<typename tname> class C
    {
    public:
        friend void f(int, C<tname>)
        {
            //mycode
        }
    };
} 

Could someone help me fix this error in my first code? Thank you very much.

The friend declaration does not mean that the function is now a member of that class. It only means that f has access to the private members of C .

So if f is in the global namespace it cannot be referenced as being inside namespace N with N::f , it is still only a ::f , even after the friend declaration.

In the second example you're declaring f as a member function and declaring it a friend which I'm not sure serves a purpose.

The following compiles:

namespace N
{

template<typename tname>
class C;

template<typename tname>
void f(int, C<tname>);

template<typename tname> class C
{
public:
    friend void f(int, C<tname>);
};
}

template<typename tname>
void N::f(int, N::C<tname>)
{
}

int main()
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM