I’m trying to write a generic wrapper in C++. Here is what I’ve written so far:
//primary template
template<typename T>
class function
{
};
//partially specialized template
template<typename T, typename U, typename V>
class wrapper<T(U,V)>
{
private:
//typedef pointer to function
typedef T (*pfn)(U,V);
pfn f;
public:
wrapper(pfn func):f(func)
{
};
T operator()(U a, V b)
{
return f(a,b);
}
};
Which can be instantiated using, for example:
wrapper<double(double, double)> someWrapper( &someFunction );
I was wondering if somebody could point me in the right direction in terms of how to modify the wrapper template to be able to instantiate in the following ways as well:
wrapper<double(double, double)> somewrapper( &someClass, &someClass::someFunction)
wrapper<double(someClass*, double)> somewrapper( &someClass::someFunction)
I’d appreciate any help in this.
Use
std::functioninstead, or the Boost implementation if your compiler does not have TR1 yet. That said, this is the specialization you are looking for pointer to member functions:and its instantiate like this:
The first instantiation you gave is not impossible, but it needs a massive ammount of type erasure to get it to work, since the class type can’t be deduced from the constructor argument.
The second one could be made to work, modifying my example code a bit, assuming you only want to instantiate it with pointer to member functions.
Assuming you want a single wrapper definition to be usable for both free and member functions with compatible arguments, you need again some type erasure to make it work. The implementation of
Boost.Functionactually uses a different technique to avoidvirtualcalls.