静态模板成员函数的实例化?

Instantiation of static template member function?

鉴于这段代码,我遇到了问题:

class Thread{
    private:
    template<class t_Funtion, class ... t_Args>
    struct ThreadExiter
    {
        using CallbackType = decltype(std::bind(std::declval<t_Funtion>(), std::declval<t_Args>()...));

        static CallbackType m_Callback;

        template<class ... t_ConstructorArgs>
        ThreadExiter(t_Funtion p_Function, t_ConstructorArgs ... p_Args) :
            m_Callback(std::forward<t_Funtion>(p_Function), std::forward<t_ConstructorArgs&&>(p_Args) ...)
        {
            // Nothing to do
        }
        ~ThreadExiter()
        {
            m_Callback();
        }
    };

如何实例化静态成员 static CallbackType m_Callback;

我试过了:

template<class t_Funtion, class ... t_Args> 
typename Thread::ThreadExiter<t_Funtion, t_Args...>::CallbackType Thread::ThreadExiter<t_Funtion, t_Args...>::m_Callback

但是我得到了:

error: no matching function for call to 'std::_Bind<int (*(Thread*)) Thread*)>::_Bind()'  typename Thread::ThreadExiter<t_Funtion, t_Args...>::CallbackType Thread::ThreadExiter<t_Funtion, t_Args...>::m_Callback;
                                                               ^

你在 ThreadExiter 的构造函数中尝试构造静态成员时出错:

ThreadExiter(/*...*/) : m_Callback(/*...*/) {}

给你:

class Thread
{
private:
    template<class t_Funtion, class ... t_Args>
    struct ThreadExiter
    {
        using CallbackType = decltype(std::bind(std::declval<t_Funtion>(), std::declval<t_Args>()...));

        static CallbackType m_Callback;

        template<class ... t_ConstructorArgs>
        ThreadExiter(t_Funtion p_Function, t_ConstructorArgs ... p_Args)
        {
            m_Callback = CallbackType{std::forward<t_Funtion>(p_Function), std::forward<t_ConstructorArgs&&>(p_Args) ...};
        }
        ~ThreadExiter()
        {
            m_Callback();
        }
    };
};

template<class t_Funtion, class ... t_Args> 
typename Thread::ThreadExiter<t_Funtion, t_Args...>::CallbackType Thread::ThreadExiter<t_Funtion, t_Args...>::m_Callback;

谢谢!最后我这样解决了(因为我没有复制和赋值构造函数):

     static CallbackType* m_Callback;
        template<class ... t_ConstructorArgs>
        ThreadExiter(t_Funtion p_Function, t_ConstructorArgs ... p_Args)
        {
            static CallbackType l_Callback(std::forward<t_Funtion>(p_Function), std::forward<t_ConstructorArgs&&>(p_Args) ...);
            m_Callback = &l_Callback;
        }

        ~ThreadExiter()
        {
            m_Callback->operator()();
        }

以这种方式实例化:

Template<class t_Funtion, class ... t_Args>
using CallbackType = decltype(std::bind(std::declval<t_Funtion>(), 
std::declval<t_Args>()...));

template<class t_Funtion, class ... t_Args>
CallbackType<t_Funtion, t_Args...>* Thread::ThreadExiter<t_Funtion, t_Args...>::m_Callback;