c++ - 从方法参数推断模板

标签 c++ c++11

<分区>

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

我有这个类(class),基于文章 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> 吗?在创建委托(delegate)时,让编译器为我解决这个问题?我希望能够按照 DelegateFactory::from_member<Foo, &Foo::foo>(&f) 的方式说些什么.

最佳答案

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

关于c++ - 从方法参数推断模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453460/

相关文章:

c++ - 使用 MTL/Boost 库 Mac 终端 C++

c++ - 如何通过引用为 C++0x 传递 Lambda 表达式参数

c++ - 如何使用带有可变参数的动态转换?

c++ - 为什么 C++11 move 运算符 (=) 的行为不同

c++ - 如何在 header 中声明由函数初始化的全局常量?

c++ - 模板模板函数实例化

c++ - setw 没有按预期工作

c++ - 如果已知访问顺序是安全的,如何在没有互斥锁的情况下同步线程/CPU?

c++ - 如何使用 lock_guard 和 try_lock_for

c++ - 哪个功能结构更好?