Search code examples
c++templatesforward-declaration

Forward declaration of template class member function


This is forward declaration of Mappings class:

template<typename Type, typename IDType=typename Type::IDType>
class Mappings;

template<typename Type, typename IDType>
class Mappings
{
public:
    ...
    Type valueFor(const IDType& id);
    ...
};

How can i forward declare valueFor function?

I need something like

template<typename Type, typename IDType>
Type Mappings::valueFor(const IDType& id)
{
    // return value 
}

Solution

  • As has already been pointed out in the comments above, it's not possible to forward declare just a single member function of a class. If what you're actually looking for is a way to define your member function outside of the class:

    template <typename Type, typename IDType = typename Type::IDType>
    class Mappings;
    
    template <typename Type, typename IDType>
    class Mappings
    {
    public:
        Type valueFor(const IDType& id);
    };
    
    template <typename Type, typename IDType>
    Type Mappings<Type, IDType>::valueFor(const IDType& id)
    {
        return {};
    }
    

    live example here

    Note that the class name before the :: needs to include the template arguments. In the definition of a member function outside of the class definition, the name must be qualified by the class name [class.mfct]/4 followed by ::. Mappings is the name of a class template, not the name of a class. While, inside the definition of a class template, the name of the template can be used synonymously with the name of the class [temp.local]/1, we are not inside the definition of any template at the point where the definition of this member function is introduced. Thus, you need to use the proper name of the class there…