Home > Blockchain >  class template and member function template with requires
class template and member function template with requires

Time:07-09

I have a template class called Speaker, with a template member function called speak. These both have a requires clause. How do I define the member function outside of the class in the same header file?

// speaker.h

#include <concepts>

namespace prj
{
    template <typename T>
    requires std::is_integral<T>
    struct Speaker
    {
        template <typename U>
        requires std::is_integral<U>
        const void speak(const Speaker<U> &speaker);
    };

    // what do I put here?
    const void Speaker<T>::speak(const Speaker<U> &speaker)
    {
        // code
    }
}

CodePudding user response:

The rules for defining template members of class templates are the same in principle as they were since the early days of C .

You need the same template-head(s) grammar component(s), in the same order

template <typename T> requires std::is_integral_v<T>
template <typename U> requires std::is_integral_v<U>
const void Speaker<T>::speak(const Speaker<U> &speaker)
{
        // code
}

The associated constraint expression and template <...> form the template-head together.


As an aside:

  • const qualified return types are redundant in the best case, or a pessimization in the worst case. I wouldn't recommend it (especially over void).
  • I'd also recommend using concepts (std::integral) if including the library header, not type traits (std::is_integral) that may or may not be included. The concepts allow for the abbreviated syntax, which is much more readable:
    template<std::integral T>
    template<std::integral U>
    
  • Related