c++静态编译错误使用模板

C++ static compile error using templates

本文关键字:错误 静态 编译 c++      更新时间:2023-10-16

我有

template < typename threadFuncParamT >
class ThreadWrapper
{
public:
    static int ThreadRoutineFunction(void* pParam);
    int ExecuteThread();
    ThreadWrapper(ThreadPool<threadFuncParamT> *pPool);
};
template<typename threadFuncParamT>
int ThreadWrapper<threadFuncParamT>::ThreadRoutineFunction(void* pParam)
{
    ThreadWrapper<threadFuncParamT> *pWrapper = reinterpret_cast<ThreadWrapper<threadFuncParamT>*>(pParam);
        if(pWrapper != NULL)
{
        return pWrapper-ExecuteThread(); // Error here.
    }
    return 0;
}
template < typename threadFuncParamT >
ThreadWrapper<threadFuncParamT>::ThreadWrapper(ThreadPool<threadFuncParamT> *pPool)
{
    ThreadWrapper<threadFuncParamT>::m_pThreadPool = pPool;
    m_tbbThread = new tbb::tbb_thread(&(ThreadWrapper<threadFuncParamT>::ThreadRoutineFunction), this);
    if (m_tbbThread->native_handle() == 0)
    {
        delete m_tbbThread;
        m_tbbThread = NULL;
        // TODO: throw execption here or raise assert.
    }
}

我得到的错误如下C2352: 'ThreadWrapper::ExecuteThread':非法调用非静态成员函数

我正在VS2010上编译。

这里有谁能帮我清除这个错误吗?

谢谢!

问题是你的错误行

return pWrapper-ExecuteThread(); // Error here.

缺失一个>;应该是

return pWrapper->ExecuteThread(); // Error here.

你得到这样一个奇怪的编译错误,因为它试图执行减法;指针pWrapper被视为一个整数,调用ExecuteThread()返回的值(它产生一个int)从中减去。然而,ExecuteThread()既不是全局函数,也不是静态成员函数——因此编译器会报错。

您错过了电话中的>。你想要return pWrapper->ExecuteThread();

你错过了">"这是

pWrapper->ExecuteThread()

pWrapper-ExecuteThread()

不能用这种语法调用静态成员函数。试着这样做:

static_cast<ThreadWrapper*>(pParam)->ExecuteThread();

可能是多余的,但是解释一下:作为线程入口点的函数不能是实例方法,它们必须是文件作用域函数或静态方法。常用的习惯用法是将一个void指针传递给静态/全局线程启动例程,将该指针强制转换为正确的类类型,并使用它来调用将在另一个线程中执行的实际实例方法。