如何将参数包存储为成员

时间:2015-10-31 01:50:51

标签: c++ visual-c++

所以我正在读这个帖子:C++ How to store a parameter pack as a variable

答案对我没有帮助(我不确定如何实施)

我正在尝试创建的是一个包含参数的Thread类,当前我这样做的参数需要能够存储为成员,以便将它们传递给成员函数。

这是我当前的Thread类:(我希望所有的FuncArgs都能够存储为成员,因此可以将它们传递给Run中的成员函数)

template<class _Ty, typename...FuncArgs>
    class YThread
{
private:

    typedef YVoid(_Ty::* YMethod)();

    HANDLE _myThread_handle;
    DWORD  _myThread_id;
    _Ty* _myObject;
    YMethod _myMethod;



private:
    static YVoid Run(YPointer thread_obj)
    {
        YThread<_Ty>* thread = (YThread<_Ty>*)thread_obj;
        thread->_myObject->*thread->_myMethod();
    }
    YThread(const YThread<_Ty>& Other) = delete;
    YThread<_Ty>& operator=(const YThread<_Ty>& other) = delete;

public: // Starters
    YThread()
    {}
    YThread(_Ty* object, YVoid(_Ty::* method)())
    {
        _myObject = object;
        _myMethod = method;
        Start();
    }

    ~YThread()
    {
        if (_myThread_handle)
            CloseHandle(_myThread_handle);
    }

    YBool Start()
    {
        _myThread_handle = CreateThread(
            0, 0,
            (LPTHREAD_START_ROUTINE)YThread<_Ty>::Run,
            this,
            0, &_myThread_id);
    }

    YBool Start(_Ty* object, YVoid(_Ty::* method)())
    {
        _myObject = object;
        _myMethod = method;
        Start();
    }

public: // Other
    YVoid Kill()
    {
        TerminateThread(_myThread_handle, 0);
    }

    YVoid Join()
    {
        WaitForSingleObject(_myThread_handle, INFINITE);
    }

    YBool is_alive()
    {
        DWORD exitCode = 0;
        if (_myThread_handle)
            GetExitCodeThread(_myThread_handle, &exitCode);
        if (exitCode == STILL_ACTIVE)
            return true;
        return false;
    }

};

1 个答案:

答案 0 :(得分:1)

我认为你是出于教育目的而这样做 - 因为否则,我强烈建议你不要重新发明轮子,并按照自然意图使用std::thread

那说 - 沿着这些方向,也许是:

class YThread {
  std::function<void()> thing_to_run;
public:
  template<class Ty, typename... FuncArgs>
  YThread(Ty* object, YVoid(Ty::* method)(FuncArgs...),
          FuncArgs&&... args) {
    thing_to_run = [=](){ (object->*method)(std::forward<FuncArgs>(args)...); };
  }
  // When it comes time to actually run the method, just do
  //   thing_to_run();
};