std::bind 可变参数模板函数

 

#include 
#include 
#include 

using namespace std;

class TestBindVar
{
public:
    template
    void Init(T&... args)
    {
        cout << __FUNCTION__ << endl;
        Print(args...);

        // 方法1
        {
            mf_ = std::bind(&TestBindVar::Reset, this, args...);
            std::cout << __FUNCTION__ << "==> " << __LINE__ << std::endl;
            mf_();
        }

        // 方法2
        {
            void (TestBindVar::*FuncPointer)(T&...) = &TestBindVar::Reset;
            mf_ = std::bind(FuncPointer, this, args...);
            std::cout << __FUNCTION__ << "==> " << __LINE__ << std::endl;
            mf_();
        }


        // 方法3
        {
            using FuncType = void(TestBindVar::*)(T&...);
            mf_ = std::bind(FuncType(&TestBindVar::Reset), this, args...);
            std::cout << __FUNCTION__ << "==> " << __LINE__ << std::endl;
            mf_();
        }

    }

    template
    void Reset(T&... args)
    {
        cout << __FUNCTION__ << endl;
    }

    // std::function to Reset(...)
    std::function mf_;

private:
    template
    void Print(First& arg)
    {
        cout << arg << endl;
    }

    template
    void Print(First& arg, Rest&... args)
    {
        cout << arg <<"";
        Print(args...);
    }
};

int main()
{
    int arg1 = 1;
    double arg2 = 2.5;
    string arg3 {"test_bind" };

    TestBindVar TestBindVar;
    TestBindVar.Init(arg1, arg2, arg3);

    return 0;
}

 

你可能感兴趣的:(c++)