Abstract Static Methods

I

Icosahedron

I know that virtual static methods have been addressed, and I'm
not really
looking for virtual methods, because I don't really need the run
time dispatching.
What I would like is to have compile time enforcement of the
definition of
a couple of static methods on all classes that inherit from a
certain
class. Unfortunately I haven't quite stumbled upon it. Even a
static assert
would be better than nothing.

The best I've been able to come up with is:

std::list<bool (*)(void)> callbacks;

template <typename T>
struct A {

template <typename Y>
struct static_init {
static_init(void) { }
// just ignore for the moment that this returns void :)
static const bool registered = callbacks.push_back(
&Y::c1 );
};

static_init<T> stupid;
};

struct B : public A<B> {

static bool c1(void);
};

struct C : public A<C> {

static bool c1(void);
};

bool B::c1(void)
{
return true;
}

bool C::c1(void)
{
return false;
}

which doesn't compile due to the incomplete types that B and C
are by the
time the call to c1 is compiled. This is on g++ 3.2.3.

As you can see, what I'm trying to do is for any class
instantiated, I would like the program to add a static method of
that class to a list of callbacks before the object is actually
created. Any ideas on implementing this would be appreciated.
 
V

Victor Bazarov

Icosahedron said:
I know that virtual static methods have been addressed, and I'm
not really
looking for virtual methods, because I don't really need the run
time dispatching.
What I would like is to have compile time enforcement of the
definition of
a couple of static methods on all classes that inherit from a
certain
class. Unfortunately I haven't quite stumbled upon it. Even a
static assert
would be better than nothing.

I don't know any mechanism in C++ (besides pure virtual function)
that would force a derived class to do anything, like implementing
a function. That's why the most often recommended path is to
thoroughly document what you need the user of your class to do to
change the default behaviour and actually provide that default
behaviour. Since your callbacks return either true or false, make
the default one return true and those classes who want to override
that will return false.

V
 

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
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top