gpt4 book ai didi

c++ - 为什么模板化友元函数在类中定义时似乎没有公开?

转载 作者:行者123 更新时间:2023-11-30 05:15:59 24 4
gpt4 key购买 nike

<分区>

这似乎可行:

template<class A> struct S {
template<class B> friend S<B> f(B);
};

template<class B> S<B> f(B) {return S<B>{};}

int main() {
f(5);
}

http://ideone.com/lApGTi

好的,让我们做一个看似纯粹的外观更改,将 f 的定义移动到 struct 的主体中:

template<class A> struct S {
template<class B> friend S<B> f(B) {return S<B>{};}
};

int main() {
f(5);
}

突然编译开始失败:

prog.cpp: In function ‘int main()’:
prog.cpp:6:5: error: ‘f’ was not declared in this scope
f(5);
^

http://ideone.com/ImsQtJ

为什么需要在类外部定义模板友元函数才能在此代码段中工作?

是否有任何技巧可以让函数 f 在类定义的主体中定义?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com