我有一个问题,给出这段代码:
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;
^
答案 0 :(得分:1)
在尝试在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;
答案 1 :(得分:0)
谢谢!最后我以这种方式解决了(因为我没有复制和赋值构造函数):
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;