如何修复 gcc 警告“友元声明声明非模板函数”

Pau*_* II 2 c++ templates gcc-warning language-lawyer c++14

所以我这里有一些使用 gcc、clang 和 msvc 编译的代码:

#include <cstdio>
#include <type_traits>

struct c_class;

template <class T> struct holder { friend auto adl_lookup(holder<T>); };

template <class C, class T> struct lookup {
  friend auto adl_lookup(holder<T>) { return holder<C>{}; }
};

struct cpp_class : lookup<cpp_class, c_class *> {
  cpp_class() {}
};

int main() {
  static_assert(std::is_same<holder<cpp_class>,
                             decltype(adl_lookup(holder<c_class *>{}))>{},
                "Failed");
}
Run Code Online (Sandbox Code Playgroud)

之所以在类adl_lookup中定义lookup而不是在类中定义,是为了在继承CRTP类时holder可以从c_class到进行“反向”查找。所以友元函数不能移到类中。cpp_classlookup<cpp_class, c_class *>holder

但是,在 gcc 上,我收到有关非模板友元函数的警告:

<source>:9:37: warning: friend declaration 'auto adl_lookup(holder<T>)' declares a non-template function [-Wnon-template-friend]
    9 |     friend auto adl_lookup(holder<T>);
      |                                     ^
<source>:9:37: note: (if this is not what you intended, make sure the function template has already been declared and add '<>' after the function name here)
Run Code Online (Sandbox Code Playgroud)

如果我尝试通过前向声明函数然后使用 来解决此问题<>,它不会使用 gcc 或 msvc 进行编译(尽管它会使用 clang 进行编译):

<source>:9:37: warning: friend declaration 'auto adl_lookup(holder<T>)' declares a non-template function [-Wnon-template-friend]
    9 |     friend auto adl_lookup(holder<T>);
      |                                     ^
<source>:9:37: note: (if this is not what you intended, make sure the function template has already been declared and add '<>' after the function name here)
Run Code Online (Sandbox Code Playgroud)

我在这里使用符合标准的 C++(在两个片段中)吗?是否有理由担心 gcc 关于非模板朋友的警告,或者这只是我可以安全忽略的误报?

use*_*522 6

第二个片段的格式不正确,因为friend声明不能是模板专业化的定义。用于接受此问题的开放式 clang 错误报告位于此处

第一个对我来说似乎有效。

GCC 的警告很烦人,因为将非模板函数定义为友元正是您想要在此处执行的操作。不幸的是,我认为没有任何方法可以在代码中表明这确实是您想要做的,但是您可以使用 禁用警告-Wno-non-template-friend。根据文档,它的存在是出于历史原因,用于识别 ISO-C++ 之前的兼容性问题,其中语法具有不同的含义。

您应该意识到,使用这种友元注入来启用有状态元编程的能力可能被认为是该语言的意外功能,并且可能(我不知道)在将来的某个时候受到限制,请参阅此问题