Problem with function selection in templates

P

Pär Buschka

Hi there.

I have some template functions that operate on different types of object. If
the object has a certain memberfunction I want to call that function, and if
not, I want to call a global function that operates on that object.

Some pseudocode to show what I mean:

template<class T> void Function(T& MyObject)
{
if exist MyObject.Process() then MyObject.Process();
else GlobalProcess(MyObject);
}

is there a good way to do this without having to write a lot of overloaded
functions for one of the cases?

Thanks in advance
Pär Buschka
 
V

Victor Bazarov

Pär Buschka said:
I have some template functions that operate on different types of
object. If the object has a certain memberfunction I want to call
that function, and if not, I want to call a global function that
operates on that object.
Some pseudocode to show what I mean:

template<class T> void Function(T& MyObject)
{
if exist MyObject.Process() then MyObject.Process();
else GlobalProcess(MyObject);
}

is there a good way to do this without having to write a lot of
overloaded functions for one of the cases?

template<class T, bool usemember> struct ObjectProcessor;

template<class T> struct ObjectProcessor<T, true> {
void operator()(T& MyObject) {
MyObject.Process();
}
};

template<class T> struct ObjectProcessor<T, false> {
void operator()(T& MyObject) {
GlobalProcess(MyObject);
}
};

template<class T> void Function(T& MyObject)
{
ObjectProcessor<T, has_member< ??? > >()(MyObject);
}

Look up a suitable implementation of "has_member" on the Web.

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top