从方法参数中推断模板

时间:2014-08-22 18:30:52

标签: c++ c++11

有没有办法让编译器从方法的签名中推断出模板参数?

我有这个课程,基于文章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
    }
};

要实例化这个类,可以说

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);
}

我的问题是:有没有办法让编译器从方法本身推断出方法参数类型?也就是说,我可以避免在创建委托时指定<int, double>,并让编译器为我解决这个问题吗?我想能够说出DelegateFactory::from_member<Foo, &Foo::foo>(&f)

的内容

1 个答案:

答案 0 :(得分:3)

#include <iostream>

template <typename... T>
class Delegate
{
};

template <typename T, typename... Args>
Delegate<Args...> from_member(T* t, void (T::*)(Args...))
{
    return Delegate<Args...>(/* fill in, you have all data you need */);
}

struct Foo
{
    void foo(int x, double y)
    {
        std::cout << "foo(" << x << ", " << y << ")" << std::endl;
    }
};

int main()
{
    Foo f;
    auto d = from_member(&f, &Foo::foo);

    return 0;
}