为什么编译好友函数模板时会出现“-Wunsupported-friend”警告?

Why do I have `-Wunsupported-friend` warning when I compile friend function template?

提问人:myoldgrandpa 提问时间:10/15/2023 更新时间:10/15/2023 访问量:57

问:

我想将模板类的成员函数声明为朋友。但是我收到了警告消息,例如warning: dependent nested name specifier 'Schedule<T>::' for friend class declaration is not supported; turning off access control for 'Manager' [-Wunsupported-friend]

我的代码如下

template<typename T>
class Task{};

template<typename T>
class Schedule {
    public:
        void dispatch(Task<T>*) {}
};

class Manager {
    template<typename T>
    friend class Task;

    template<typename T>
    friend void Schedule<T>::dispatch(Task<T>*); // <== Warning here!!!!

    template<typename T>
    friend int ticket() {
        return ++Manager::count;
    }

    static int count;

};

是什么原因导致了此警告,我该如何解决?

C++ 模板 friend function-templates

评论

0赞 HolyBlackCat 10/15/2023
和全班同学交朋友?

答:

3赞 Ted Lyngmo 10/15/2023 #1

这是在使用 LLVM 中未完全实现的功能时收到的警告。

从 LLVM 源代码:

/// True if this 'friend' declaration is unsupported.  Eventually we
/// will support every possible friend declaration, but for now we
/// silently ignore some and set this flag to authorize all access.
unsigned UnsupportedFriend : 1;

如果您不担心授予所有成员函数的“所有访问权限”,则可以安全地忽略该警告。我假设你在编译时收到了警告,所以只需在后面添加 - 或者务实一点,让整个类成为:Schedule<T>-Weverything-Wno-unsupported-friendfriend

template<typename T>
friend class Schedule;

授权对所有成员函数的所有访问的效果可以这样说明:Schedule<T>

class Manager;

template <typename T>
class Schedule {
public:
    void dispatch() {}
    void other(Manager&);                // not befriended
};

class Manager {
public:
    template <typename T>
    friend void Schedule<T>::dispatch(); // becomes `friend class Schedule<T>;`

private:
    int x = 0;
};

template <typename T>
void Schedule<T>::other(Manager& m) {
    ++m.x;                               // should not compile, but does
}