C++ Logo

std-discussion

Advanced search

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

From: Bo Persson <bo_at_[hidden]>
Date: Sun, 24 Apr 2022 14:07:07 +0200
On 2022-04-24 at 11:07, Yongwei Wu via Std-Discussion wrote:
> 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);

That's not really an assymetry, but the correct way to do it.

Inside that class, Wrapper is a shorthand for Wrapper<T>. Outside the
class there is no shorthand available, so you need to specify its
template parameter explicitly.

And then you have to make the friend declaration match the out-of-class
definition (with an equal number of template parameters).

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

No. But it might be more convenient. And slightly better for the
compiler that doesn't have to consider the "hidden friend" (ADL only),
when Wrappers are not involved.

Received on 2022-04-24 12:07:15