簡體   English   中英

朋友聲明了一個非模板 function,即使它駐留在模板化的 class 中(僅 gcc)

[英]Friend declares a non-template function even though it resides in templated class (only gcc)

下面的示例編譯但 gcc 警告我朋友聲明實際上不是模板化的 function。我不明白我到底應該改變什么。 Clang 和 MSVC 毫無問題地接受此代碼。

這個問題中,暗示你應該將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>();
}

警告:

<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)

我該如何解決這個問題(對於 gcc)?

用於模板參數的標識符不得在模板內出於任何其他目的重復使用。 換句話說,它們可能不會被遮蔽。

如果您希望任何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>>;
};

如果您只希望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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM