Menu

false "syntax error: != <" on friend template function

2020-06-16
2020-06-16
  • David Garlisch

    David Garlisch - 2020-06-16

    Snippet compiler: https://coliru.stacked-crooked.com/view?id=1a00c4e44f0c7506

    #include <iostream>
    
    template <typename T> class Foo;
    
    template <typename T>
    bool operator==(const Foo<T> &, const Foo<T> &);
    
    template <typename T>
    bool operator!=(const Foo<T> &, const Foo<T> &);
    
    template <typename T>
    class Foo {
    public:
        Foo()
        {
        }
    
    
        //--------------------------------------------------------------------------
        //--------------------------------------------------------------------------
        // Leaving off <> makes CPPCHECK happy but generates a G++ warning
        friend bool operator== (const Foo<T> &, const Foo<T> &);
        //
        // main.cpp:24:65: warning: friend declaration 'bool operator==(const Foo<T>&, const Foo<T>&)' declares a non-template function [-Wnon-template-friend]
        // friend bool operator== (const Foo<T> &, const Foo<T> &);
        //                                                       ^
        // main.cpp:24:65:note:(if this is not what you intended, make sure
        //   the function template has already been declared and add <> after the
        //   function name here)
    
    
        //--------------------------------------------------------------------------
        //--------------------------------------------------------------------------
        // This fails CPPCHECK - but builds w/o warning on gcc 5.2 (C++11)
        // I believe this is the correct syntax for a non-inline friend template function.
        // See: Template friend operators
        // https://en.cppreference.com/w/cpp/language/friend
        friend bool operator!= <> (const Foo<T> &, const Foo<T> &);
    
    private:
        T impl_{ 0 };
    };
    
    
    template <typename T>
    bool operator== (const Foo<T> &a, const Foo<T> &b)
    {
        std::cout << "hello ==\n";
        return a.impl_ == b.impl_;
    }
    
    
    template <typename T>
    bool operator!= (const Foo<T> &a, const Foo<T> &b)
    {
        std::cout << "hello !=\n";
        return a.impl_ == b.impl_;
    }
    
    
    
    int main()
    {
        Foo<int> v1;
        Foo<int> v2;
        v1 == v2;
        v1 != v2;
    }
    
     
  • Daniel Marjamäki

    Thanks! I can reproduce. I created this ticket: https://trac.cppcheck.net/ticket/9771

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.