简体   繁体   中英

Declaring a static function of class as a friend

My question arises because, from my understanding, you must forward declare or define functions before declaring them as friends. Is the following valid?

template <typename> class class1;

template <typename T>
class class2 {
    ...
    friend void class1<T>::foo();
    ...
}

template <typename T>
class class1 {
    ...
    static void foo() {}
    ...
}

The problem here is that you can't forward declare the static function foo . Hopefully this encapsulated everything necessary for this question. I tried something like this and it compiled and worked fine, but I was wondering if this is still considered valid since I also read some compilers accept friend declarations without previous forward declarations although this is compiler dependent.

Like it or not, declaring something as friend creates forward declaration outside of the class. This is explicitly written in the standard and compilers support this.

Your example is more complicated. You are trying to use something from inside of the forward declaration. Well, smart compiler may handle this. All compilers - I am not so sure. Second point - your friend declaration is inside the template. Compilers parse templates only partially. They cannot do it better. All substitutions and checks happen only when the template is instantiated. At this point the compiler knows much more. In your sample class2 is never instantiated.

Try to write something weird inside the template and you will find that this will compile. Then add instantiation without changing the template itself. Compiler will give you errors.

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