Portál AbcLinuxu, 26. října 2025 12:35
namespace myns
{
struct myclass
{
int a() const { return 5; }
int b() const { return 6; }
int mysum() const { return a() + b(); }
};
// Enable ADL mysum call for myclass
int mysum(const myclass& m)
{
return m.mysum();
}
}
// -- 3rdparty knihovna --
namespace thirdparty
{
struct thirdpartyclass
{
int abc() const { return 5; }
int def() const { return 6; }
};
}
// -- vlastni kod, implementovat mysum pro thirdpartyclass, musi byt ve stejnem namespace jako thirdpartyclass, aby fungovalo ADL
namespace thirdparty
{
int mysum(const thirdpartyclass& t)
{
return t.abc() + t.def();
}
}
// -- pouziti v template:
namespace totalydifferentnamespace
{
template<class... T>
int getSumOfSums(const T&... t)
{
return (mysum(t) + ...); // Zde se vyuzije ADL, zavola se metoda mysum z namespace, kde je kazda trida definovana
}
}
int main()
{
myns::myclass mc;
thirdparty::thirdpartyclass t;
return totalydifferentnamespace::getSumOfSums(mc, t); // 11+11=22
}
namespace myns
{
struct myclass
{
int a() const { return 5; }
int b() const { return 6; }
int mysum() const { return a() + b(); }
};
}
// -- 3rdparty knihovna --
namespace thirdparty
{
struct thirdpartyclass
{
int abc() const { return 5; }
int def() const { return 6; }
};
}
// --
namespace totalydifferentnamespace
{
template<class... T>
int getSumOfSums(const T&... t)
{
return (t.mysum() + ...); // Zde se vyuzije ADL, zavola se metoda mysum z namespace, kde je kazda trida definovana
}
}
template<typename T>
struct mysuminterface // not specialized
{
int mysum() const { return 0; }
};
// specialzed for myns::myclass
template<>
struct mysuminterface<myns::myclass> : myns::myclass
{
using myns::myclass::mysum;
};
// specialzed for thirdparty::thirdpartyclass
template<>
struct mysuminterface<thirdparty::thirdpartyclass> : thirdparty::thirdpartyclass
{
int mysum() const { return abc() + def(); }
};
int main()
{
mysuminterface<myns::myclass> mc;
mysuminterface<thirdparty::thirdpartyclass> t;
return totalydifferentnamespace::getSumOfSums(mc, t); // 11+11=22
}
proč jakoby nestačí podědit nějakej trait a musí se 'hackovat' hotová instance?? :O :O
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.