C++ Logo

std-discussion

Advanced search

Out-of-class definition of friend function template of class template possible?

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Sun, 24 Apr 2022 17:07:40 +0800
For code like the following:

template <typename T>
class Wrapper {
public:
    Wrapper(T value) : value_(value) {}

    template <typename CharT, typename Traits>
    friend std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
               const Wrapper& obj)
    {
        os << obj.value_;
        return os;
    }

private:
    T value_;
};

Is there a way to move the operator<< definition outside the class template?

I have not found a direction solution, though some workarounds are
possible: say, proxying through a member function template; or make the
operator<< template have three template parameters:

    template <typename CharT, typename Traits, typename U>
    friend std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
               const Wrapper<U>& obj);

However, I am puzzled by the asymmetry: Is my original code a case where
only the inline definition is possible?

Received on 2022-04-24 09:07:38