Is there some way to have the compiler infer template arguments from a method's signature?
I have this class, based off of the article The Impossibly Fast C++ Delegates.
template<typename... Ds>
class Delegate {
public:
Delegate()
: object_ptr(0)
, stub_ptr(0)
{}
template <class T, void (T::*TMethod)(Ds...)>
static Delegate from_member(T* object_ptr)
{
Delegate d;
d.object_ptr = object_ptr;
d.stub_ptr = &method_stub<T, TMethod>; // #1
return d;
}
void operator()(Ds... ds) const
{
return (*stub_ptr)(object_ptr, ds...);
}
private:
typedef void (*stub_type)(void* object_ptr, Ds...);
void* object_ptr;
stub_type stub_ptr;
template <class T, void (T::*TMethod)(Ds...)>
static void method_stub(void* object_ptr, Ds... ds)
{
T* p = static_cast<T*>(object_ptr);
return (p->*TMethod)(ds...); // #2
}
};
To instantiate this class, one would say
struct Foo {
void foo(int x, double y) {
std::cout << "foo(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Foo f;
auto d = Delegate<int, double>::from_member<Foo, &Foo::foo>(&f);
d(1, 2.3);
}
My question is this: Is there some way to get the compiler to infer the method parameter types from the method itself? That is, can I avoid having to specify <int, double>
when creating a delegate, and have the compiler figure this out for me? I would like to be able to say something along the lines of DelegateFactory::from_member<Foo, &Foo::foo>(&f)
.