How to detect whether there is a specific member variable in class?
Posted
by Kirill V. Lyadvinsky
on Stack Overflow
See other posts from Stack Overflow
or by Kirill V. Lyadvinsky
Published on 2009-06-17T06:58:38Z
Indexed on
2010/04/22
20:13 UTC
Read the original article
Hit count: 329
For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code:
template<int> struct TT {typedef int type;};
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
struct P1 {int x; };
struct P2 {float X; };
// it also could be struct P3 {unknown_type X; };
int main()
{
P1 p1 = {1};
P2 p2 = {1};
Check_x(p1); // must return true
Check_x(p2); // must return false
return 0;
}
But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template:
template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; }
But it does not compile in GNU C++. Is there universal solution?
UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.
© Stack Overflow or respective owner