C++ Logo

std-discussion

Advanced search

Re: Templated entity: non-template friend function

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Fri, 6 May 2022 14:10:23 +0800
This is actually very similar to my question a few days ago (email titled
"Out-of-class definition of friend function template of class template
possible?").

Your problem can be solved like this:

https://gcc.godbolt.org/z/5bE3rejrE

Check my email discussion if you do not think this is good enough. I do not
like it very much either.

On Thu, 5 May 2022 at 17:28, Vladimir Grigoriev via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> Try this code
>
> https://gcc.godbolt.org/z/Mrb3WzMv7
>
> If to write
>
> inline X<256> operator+(const X<256>&, const X<256>&) noexcept;
>
> then the error message is
>
> <source>:24: undefined reference to `S::operator+(S::X<256u> const&,
> S::X<256u> const&)'
>
>
>
>
> You can meet me at http://cpp.forum24.ru/ or www.stackoverflow.com or
> http://ru.stackoverflow.com
>
>
>
> Четверг, 5 мая 2022, 3:35 +03:00 от Brian Bi <bbi5291_at_[hidden]>:
>
> On Wed, May 4, 2022 at 4:47 PM Vladimir Grigoriev via Std-Discussion <
> std-discussion_at_[hidden]
> <//e.mail.ru/compose/?mailto=mailto%3astd%2ddiscussion_at_[hidden]>>
> wrote:
>
> The following program
>
> namespace S
> {
>
>
> It looks like the "namespace S\n{" before this line is a typo. Is that so?
>
> I removed them, and the rest of the program compiles fine in GCC and
> Clang. https://godbolt.org/z/fYd8fhrjb
>
>
> #include <iostream>
>
> namespace S
> {
>
> template <unsigned N>
> class X
> {
> public:
> int i = N;
>
> friend X operator+( const X &a, const X &b ) noexcept
> {
> return { .i = a.i + b.i };
> }
> };
>
> inline X<256> operator+( const X<256> &a, const X<256> &b ) noexcept;
>
> }
>
> int main()
> {
> S::X<256>( *ptr )( const S::X<256>&a, const S::X<256>&b ) noexcept
> = &::S::operator+;
>
> std::cout << ptr( S::X<256>(), S::X<256>() ).i << '\n';
> }
>
> compiles using MS VC++ (2019) but does not compile using gcc or clang.
>
> I suspect that the problem is that the friend function is a templated
> entity that is not instantiated when the class granting friendship is
> instantiated.
>
> On the other hand, this behavior contradicts the behavior when the class
> is not a template class. Should the friend function be instantiated in such
> a case?.
>
> With best regards
> (Vlad from Moscow)
> You can meet me at http://cpp.forum24.ru/ or www.stackoverflow.com or
> http://ru.stackoverflow.com
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> <//e.mail.ru/compose/?mailto=mailto%3aStd%2dDiscussion_at_[hidden]>
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>
>
>
> --
> *Brian Bi*
>
>
>
>
>
> --
> Std-Discussion mailing list
> Std-Discussion_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>


-- 
Yongwei Wu
URL: http://wyw.dcweb.cn/

Received on 2022-05-06 06:10:30