Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Compile Time decision static or member

0 views
Skip to first unread message

Anees

unread,
Jun 1, 2009, 8:18:53 AM6/1/09
to
Dear Fellows:

I have following scenario:

class A {
public:
void me_print () { cout << "A" << endl; }
static void print() { cout << "static A" << endl; }
};

class B {
};

class C : public A, public B {
public:
void foo() { PRINT; }
};

class D: public B {
public:
void foo() { PRINT; }
};


int _tmain(int argc, _TCHAR* argv[])
{
C c;
D d;

c.foo();
d.foo();

return 0;
}

I want to define a macro (#define) such that when instance of A's
derived class (i.e. C) call PRINT; it gets A's member method me_print
(), and when instance of NON A's derived class (i.e. D) call PRINT, it
should be resolved to A's static subroutine print().

Thank you.


Regards,

Anees Haider

Maxim Yegorushkin

unread,
Jun 1, 2009, 8:42:07 AM6/1/09
to

You don't need a macro for that, you can do that in pure C++ (for
clarity, I changed class to struct and removed all public keywords):

struct A {
void me_print () { std::cout << "A\n"; }
static void print() { std::cout << "static A\n"; }
};

void do_print(A* a) { a->me_print(); }
void do_print(void*) { A::print(); }

struct B {};

struct C : A, B {
void foo() { do_print(this); }
};

struct D : B {
void foo() { do_print(this); }
};

int main()


{
C c;
D d;
c.foo();
d.foo();
}

The idea here is that there are two overloads of do_print(). One takes
A*, the other one void*. The first one is chosen when you pass A* or
its publicly derived sub-class pointer. The void* overload is chosen
for all other pointers.

--
Max

Anees

unread,
Jun 1, 2009, 9:00:49 AM6/1/09
to
On Jun 1, 6:42 pm, Maxim Yegorushkin <maxim.yegorush...@gmail.com>
wrote:
> Max- Hide quoted text -
>
> - Show quoted text -

Thanks Max, it works :)

0 new messages