[英]Friend declares a non-template function even though it resides in templated class (only gcc)
The following example compiles BUT gcc warns me that the friend declaration is in fact not a templated function. I don't understand what exactly I'm supposed to change.下面的示例编译但 gcc 警告我朋友声明实际上不是模板化的 function。我不明白我到底应该改变什么。 Clang and MSVC accept this code without any issues.
Clang 和 MSVC 毫无问题地接受此代码。
In this this question it is implied that you're supposed to put template <typename T>
in front of the in-class friend declaration, but then gcc complains about shadowing T.在这个问题中,暗示你应该将
template <typename T>
放在类内朋友声明的前面,但随后 gcc 抱怨隐藏 T。
#include <memory>
#include <cstdio>
/* header.hpp */
template <typename T>
class entity;
template <typename T>
auto create_entity() -> std::shared_ptr<entity<T>>;
template <typename T>
class entity
{
// template <typename T>
friend auto create_entity() -> std::shared_ptr<entity<T>>;
};
/* impl.cpp */
template <typename T>
auto create_entity() -> std::shared_ptr<entity<T>> {
return std::make_shared<entity<T>>();
}
int main()
{
create_entity<int>();
}
Warning:警告:
<source>:16:41: warning: friend declaration 'std::shared_ptr<entity<T> > create_entity()' declares a non-template function [-Wnon-template-friend]
16 | friend auto create_entity() -> std::shared_ptr<entity<T>>;
| ^~~~~~~~~~~~~~~~~~~~~
<source>:16:41: note: (if this is not what you intended, make sure the function template has already been declared and add '<>' after the function name here)
How do I resolve this issue (for gcc)?我该如何解决这个问题(对于 gcc)?
Identifiers used for template parameters may not be re-used inside the template for any other purpose.用于模板参数的标识符不得在模板内出于任何其他目的重复使用。 In other words, they may not be shadowed.
换句话说,它们可能不会被遮蔽。
If you want any create_entity<U>
to be a friend of entity<T>
, change the inner T
to U
:如果您希望任何
create_entity<U>
成为entity<T>
的友元,请将内部T
更改为U
:
template <typename T>
auto create_entity() -> std::shared_ptr<entity<T>>;
template <typename T>
struct entity
{
template <typename U>
friend auto create_entity() -> std::shared_ptr<entity<U>>;
};
If you want only create_entity<T>
to be a friend of entity<T>
:如果您只希望
create_entity<T>
成为entity<T>
的好友:
template <typename T>
auto create_entity() -> std::shared_ptr<entity<T>>;
template <typename T>
struct entity
{
friend auto create_entity<T>() -> std::shared_ptr<entity<T>>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.