Date: Wed, 04 May 2022 23:46:36 +0300
The following program
namespace S
{
#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
namespace S
{
#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
Received on 2022-05-04 20:47:00