Re: passing functor or function to template class
Christof,
Yes, that indeed breaks the CRTP as the Reference indirectly
tries to instantiate the object when it checks for ptr.
It turns out that you actually do not need the above-mentioned
ellipsis, but a simple partial specialization works. That should
work even the existence of CRTP.
Note: I noticed that now you essentially store every functor as
reference, I guess the life-time requirements then has to be
made clear to the caller side.
-- CODE --
#include <iostream>
template < typename T >
struct StorageSelector
{
typedef T & type;
};
template < typename T >
struct StorageSelector < T * >
{
typedef T * type;
};
// A function.
void *function() {
std::cout << "function" << std::endl;
return 0;
}
// A functor.
class Functor {
public:
Functor() {}
void *operator()() {
std::cout << "functor" << std::endl;
return 0;
}
private:
Functor(const Functor &);
} functor;
template<typename T>
struct Reference
{
typedef typename StorageSelector< T >::type StorageT;
Reference( StorageT t ) : f( t ) {}
StorageT f;
};
struct X: public Reference<X>
{
X(): Reference<X>(*this) {}
void operator()() {std::cout << "functor with CRTP" << std::endl;}
} x;
int main() {
Reference<void *(*)()> rf(function);
Reference<Functor> rF(functor);
rf.f();
rF.f();
return 0;
}
-- /CODE --
On Tuesday, 10 July 2012 10:14:58 UTC-4, Christof Warlich wrote:
Hi,
I'm working at a generic library that must accept either function poi=
nters or functors to be passed to a template class. This works quite straig=
ht forward as long as both are being passed by value. But as the functors t=
hat 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 cou=
ld fix this by partial specialization (see code below), this looks rather c=
lumpsy 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 qu=
ite 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;
}