Determining member order

C

cpp_weenie

Hello group,

Should the program below be valid? Or should it generate a compilation
error? Any references to the Standard would be appreciated...

Thanks!


#include <iostream>

using namespace std;

struct foo
{
int a;
int b;
};

template<typename T1, typename T2, typename T3>
bool before(T2 T1::*mem1, T3 T1::*mem2)
{
return mem1 < mem2;
}

int main()
{
if (before(&foo::a, &foo::b))
cout << "foo::a comes before foo::b in memory" << endl;
else
cout << "foo::b comes before foo::a in memory" << endl;

return 0;
}
 
D

David White

cpp_weenie said:
Hello group,

Should the program below be valid? Or should it generate a compilation
error? Any references to the Standard would be appreciated...

Thanks!


#include <iostream>

using namespace std;

struct foo
{
int a;
int b;
};

template<typename T1, typename T2, typename T3>
bool before(T2 T1::*mem1, T3 T1::*mem2)
{
return mem1 < mem2;
}

int main()
{
if (before(&foo::a, &foo::b))

Since you can't have an array of members of foo, I would expect a
compilation error (and, in fact, I get one). The '<' operator for addresses
only makes sense when those addresses belong to the same array.

int a[10];
int *pa = &a[0];
int *pb = &a[5];
++pa; // okay
--pb; // okay
bool ba = pa < pb; // okay
int j = pb - pa; // okay

These are all okay because an int * can point to anywhere within the same
int array.

int foo::*pf = &foo::a;
int foo::*pg = &foo::b;
++pf; // error
--pg; // error
bool bf = pf < pg; // error
int k = pg - pf; // error

The same is not true of pointers to members. It simply doesn't make sense to
compare two of them.

I don't have any standard references.

DW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,824
Members
47,371
Latest member
Brkaa

Latest Threads

Top