specializing member S::display requires ‘template<>’ syntax

后端 未结 2 2222
眼角桃花
眼角桃花 2020-12-11 08:05

I\'m creating a trait class to help with my program. I have a template class called operations that contains the methods display and area

相关标签:
2条回答
  • 2020-12-11 08:06
    template< typename P > // P is declared here
    struct operations  {
        ... // into this scope
    }; // but it goes out of scope here
    
    template< typename P > // So it needs to be redeclared
    void operations::display( Rectangle const &, std::ostream &) {
        ... // for this scope.
    }
    

    The function display doesn't "own" the names of its parameters. The template parameter must be redeclared in the definition. The compiler message is referring to template<> syntax to suggest you place something inside the <> brackets, but confusingly, leaving the brackets empty and literally saying template<> means something else — explicit specialization, which isn't what you want here.

    On the other hand, static is a property of a member function which does not get mentioned in the definition. The compiler remembers static after using the other parts of the definition signature to match it to the declaration signature. So, you should erase static from the definition.

    0 讨论(0)
  • 2020-12-11 08:10

    Your functions : display and area should be write like this:

        template <>
        double operations<Rectangle>::area( Rectangle const& rect )
        {
                double width =  get<0>(rect);
                double height = get<1>(rect);
    
                return width * height;
        }
    
    • As for template specialized functions, template <> should be placed at the head of the function.
    • For static member functions, static should not appear at the definition body of the function.
    0 讨论(0)
提交回复
热议问题