C

#### christof.warlich1

I'm working at a generic library that must accept either function pointers or functors to be passed to a template class. This works quite straight forward as long as both are being passed by value. But as the functors that need to be passed may not be copyable, I'd like to pass functors by reference.. But doing this breaks the function pointer case. Although I could fix this by partial specialization (see code below), this looks rather clumpsy to me: It there a better way to deal with this situation? Take into account that my template class is quite big, so that specializing causes quite some code duplication.

Thanks for any ideas,

Chris

#include <iostream>

// A function.

void *function() {

std::cout << "function" << std::endl;

return 0;

}

// A functor.

struct Functor {

void *operator()() {

std::cout << "functor" << std::endl;

return 0;

}

} functor;

// Both classes (struct Value and struct Reference) may

// be instantiated with either a function or a functor.

template<typename T> struct Value {

Value(T t):f(t) {}

T f;

};

template<typename T> struct Reference {

Reference(T &t):f(t) {}

T &f;

};

// Partial specialization of struct Reference for

// (function) pointers).

template<typename T> struct Reference<T *> {

Reference(T t):f(t) {}

T *f;

};

// Test if it works.

int main() {

Value<void *(*)()> vf(function);

Value<Functor> vF(functor);

vf.f();

vF.f();

Reference<void *(*)()> rf(function);

Reference<Functor> rF(functor);

rf.f();

rF.f();

return 0;

}