[英]friend template function of template class
I have the following simplified code: 我有以下简化代码:
template <class T>
class A
{
public:
template <class U>
static U foo(T* p)
{
p;
return U();
}
};
class B
{
/*template <class T>
template <class U>
friend U A<T>::foo<U>(T*);*/
friend B A<B>::foo<B>(B*);
B()
{}
public:
};
...
A<B>::foo<B>(nullptr);
And it works quite well. 而且效果很好。 But the things that I've not managed to do are commented:
但是我没有做的事情被评论:
/*template <class T>
template <class U>
friend U A<T>::foo<U>(T*);*/
I don't know what the syntax I should use to make it works. 我不知道我应该使用什么语法来使其工作。 So I need to generalize my friend declaration to all possible types.
因此,我需要将我的朋友声明概括为所有可能的类型。 I've tried quite a few variants of syntax but had no success.
我尝试了很多语法变体,但没有成功。 Could some one point me out what should I write instead of my commented code to make it works?
有人可以指出我应该写些什么而不是注释的代码来使其起作用吗? Thanks!
谢谢!
What you're looking for is 您正在寻找的是
template <class T>
template <class U>
friend U A<T>::foo(T*);
The following works on IdeOne.com IdeOne.com上的以下作品
#include <iostream>
template <class T>
class A
{
public:
template <class U>
static U foo(T* p)
{
p;
return U();
}
};
class B
{
template <class T>
template <class U>
friend U A<T>::foo(T*);
B() {}
public:
void hello() const
{
std::cout << "I'm a B!" << std::endl;
}
};
int main(int, char*[])
{
A<B>::foo<B>(NULL).hello();
}
I will agree with the othe commenters, friends and templates simply don't mix, at least not in any consistent way with across a range of compilers. 我将同意其他评论者,朋友和模板完全不混在一起的观点,至少不会以任何一致的方式与各种编译器混在一起。 The standard probably states exactly what should work, though that will likely not help you.
该标准可能会确切说明应该起作用的内容,尽管这可能对您没有帮助。 Sad but true.
悲伤但真实。
Friend is often not a good idea anyhow, it might be better to consider how to write the code without friendship, or use the "poor man's friend" of a public method with a comment indicating it is not for general use. 无论如何,“朋友”通常不是一个好主意,最好考虑在没有友谊的情况下如何编写代码,或者使用公开方法的“穷人朋友”,并在注释中指出它不适合一般用途。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.