如何使模板参数的构造函数成为朋友? [英] How do I make a template parameter's constructor a friend?
问题描述
在C ++ 11中,他们使得可以简单地与 friend T
成为模板参数的朋友.您还可以使用 friend T :: Method()
将该参数内的方法作为朋友.
In C++11, they made it possible to friend a template parameter simply with friend T
. You can also friend methods within that parameter with friend T::Method()
.
但是,您如何与模板参数的构造函数成为朋友?
However, how do you friend a template parameter's constructor?
class BeMyFriend
{
public:
BeMyFriend& operator=(const BeMyFriend& rhs) = default;
BeMyFriend(const BeMyFriend& rhs) = default;
};
template<class T>
class Test
{
friend T& T::operator=(const T&); //Works fine, no error
friend T::T(const T&); //error: prototype for 'BeMyFriend::BeMyFriend(const BeMyFriend&)' does not match any in class 'BeMyFriend'
};
int main()
{
Test<BeMyFriend> hmm;
return 0;
}
我可以将模板参数的 operator =
很好地作为朋友,但是我不能与 T :: T(const T&)
成为朋友.
I'm able to friend the template parameter's operator=
just fine, but I'm unable to friend T::T(const T&)
.
如何使 friend T :: T(const T&);
工作?
这似乎是与要使构造函数成为朋友的问题不同的问题模板类.那里的问题是在声明中处理圆形模板参数.它不处理实际模板参数的构造函数.
edit: This appears to be a different issue than what is solved in Make Friend the constructor of a template class. The issue there is dealing with circular template parameters in a declaration. It doesn't deal with the constructor of an actual template parameter.
Foo
的类型是普通的模板化类,在我的示例中不是像 T
这样的模板参数.该提交中的 friend Foo< B> :: Foo< B>()
之类的东西应该可以很好地编译,这与我在 friend T :: T(const T&;)
.
The type of the Foo
is a normal templated class, not a template parameter like T
in my example. Something like friend Foo<B>::Foo<B>()
from that submission should compile just fine, unlike the issue I'm having here with friend T::T(const T&)
.
万一这很重要,我将使用gcc 7.2进行编译.
edit: In case this ends up mattering, I'm compiling with gcc 7.2.
我还想澄清一下,C ++确实支持使构造函数成为朋友.例如,第一个示例中的 friend X :: X(char),X ::〜X();
位于
edit:
I also want to clarify that C++ does support making constructors friends. For example, friend X::X(char), X::~X();
in the first example at http://en.cppreference.com/w/cpp/language/friend.
这里的问题是如何使模板参数的构造函数成为朋友.
The issue here is how to make a template parameter's constructor a friend.
推荐答案
通过在 friend
之后添加 void
,我可以在GCC中对其进行编译:
I was able to get it to compile in GCC by adding void
after friend
:
friend void T::T(const T&);
然后,我可以从 BeMyFriend
的构造函数访问 Test
的私有成员之一.但是,请注意,这是编译器特定的.我用clang尝试了一下,但没有起作用.
I was then able to access one of Test
's private members from BeMyFriend
's constructor. However, note that this is compiler specific. I tried it in clang, and it did not work.
这篇关于如何使模板参数的构造函数成为朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!