代码之家  ›  专栏  ›  技术社区  ›  Paul Fultz II

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

  •  0
  • Paul Fultz II  · 技术社区  · 4 年前

    #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");
    }
    

    原因 adl_lookup lookup 类而不是 holder c_class 到 cpp_class 当您从CRTP类继承时 lookup<cpp_class, c_class *> 班

    然而,在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)
    

    如果我试图通过向前声明函数,然后使用 <> ,它不使用gcc或msvc编译(尽管它使用clang编译):

    #include <cstdio>
    #include <type_traits>
    
    struct c_class;
    
    template <class T> struct holder;
    
    template <class T> auto adl_lookup(const holder<T> &);
    
    template <class T> struct holder {};
    
    template <class C, class T> struct lookup {
      friend auto adl_lookup<>(const 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");
    }
    

    0 回复  |  直到 4 年前
        1
  •  4
  •   user17732522    4 年前

    第二个片段的格式不正确,因为 friend 声明不能是模板专门化的定义。接受此消息的open clang bug报告是 here

    GCC发出的警告很烦人,因为在这里您想做的就是将非模板函数定义为friend。不幸的是,我不认为有任何方法可以在代码中表明这是您真正想要做的,但您可以使用禁用警告 -Wno-non-template-friend the documentation 出于历史原因,它是为了确定ISO-C++之前的兼容性问题,其中语法具有不同的含义。

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

        2
  •  0
  •   Jarod42    4 年前

    这是一个常见的错误,因为使用 if (var = foo()) 相反 if (var == foo())

    然而,添加额外的父级允许“通知”编译器的意图是 = / ==

    if ((var = foo()))
    

    没有技巧语法可以告诉您它实际上是您想要使用的非模板函数。

    还有传统的 #pragma how-to-disable-gcc-warnings-for-a-few-lines-of-code )

    推荐文章