且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模板朋友功能的前向声明

更新时间:2022-03-15 21:57:58

那是因为

friend int foo(A a);

是功能的声明,同时是朋友,但是:

is declaration of function and a friend at the same time, but:

friend T foof<>(B<T> a);

是模板实例化的朋友声明.那不一样.实例化没有声明模板功能.

Is friend declaration to template instantiation. That's different. Instantiation doesn't declare template function.

您可以成为整个函数模板的朋友,然后不需要前向声明:

You could befriend whole function template, and then forward declaration isn't needed:

template <typename T>
class B
{
private:
    T d;
public:
    B(T n){ d = n;}
    template<class U>
    friend U foof(B<U> a);
};