是否可以调用注入的朋友模板函数? [英] Is it possible to invoke an injected friend template function?
问题描述
为了与类中的其他(非模板)函数保持一致,我想定义并调用一个朋友模板函数.
To be consistent with other (non-template) functions in a class I wanted to define and invoke a friend template function.
我可以毫无问题地定义它(请参见下面的功能t
).
I can define it with no problem (see function t
below).
namespace ns{
struct S{
void m() const{}
friend void f(S const&){}
template<class T>
friend void t(S const&){}
};
template<class T>
void t2(S const& s){}
}
但是以后我无法以任何方式调用此t
函数吗?
However later I am not able to invoke this t
function in any way?
int main(){
ns::S s;
s.m();
f(s);
// t<int>(s); // error: ‘t’ was not declared in this scope (I was expecting this to work)
// ns::t<int>(s); // error: ‘t’ is not a member of ‘ns’
// ns::S::t<int>(s); // error: ‘t’ is not a member of ‘ns::S’
}
即使根本不可能,我也很惊讶能够定义它.
Even if it is not possible at all, I am surprised that I am allowed to define it.
我用gcc 8和clang 7进行了测试.
I tested this with gcc 8 and clang 7.
推荐答案
要实现此目的,需要几个前向声明.
What you need for this to work are a couple of forward declarations.
以下两行代码应位于名称空间ns
之前.
The below two lines of code should come before the namespace ns
.
struct S; //Needed because S is used as a parameter in the function template
template<class T> void t(S const&);
然后这种形式的通话将在main
内部起作用.
And then this form of call will work inside main
.
t<int>(s);
请参见演示此处.
这篇关于是否可以调用注入的朋友模板函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!