C++ Logo

std-discussion

Advanced search

Re: Templated entity: non-template friend function

From: Vladimir Grigoriev <vlad.moscow_at_[hidden]>
Date: Thu, 05 May 2022 12:27:38 +0300
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] > 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]
>>https://lists.isocpp.org/mailman/listinfo.cgi/std-discussion
>
>--
>Brian Bi
>
>
>
 

Received on 2022-05-05 09:28:02