mardi 29 janvier 2019

friend function defined inside a template class

A friend function named test() is defined inside a template class A:

template <typename T> class A {
public:
    friend void cs() {/* code */}
}

Another class inherits from template class A:

class B : public A<B> {}

In main function, I failed to call cs(), the compiler can not see its declaration if I don't provide a function declaration in the global scope:

int main(){
    cs()
}

But things are different when cs takes its template class T as a argument:

template <typename T> class A{
public:
    void cs(const T& t) {}
}

Now cs() can be successfully called in the main function without any decalration:

int main(){
    B b;
    cs(b);
}

If a function takes a user-defined class as its argument, I know the compiler would search the scope of the user-defined class. So which scope exactly is cs() defined? How it is possible that cs() is successfully called in the second case?

Aucun commentaire:

Enregistrer un commentaire