使用模板的C ++静态编译错误

时间:2011-08-04 12:34:09

标签: c++ templates

我有

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.
    }
}

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

我正在编译VS2010。

任何人都可以帮我解决这个问题。

谢谢!

4 个答案:

答案 0 :(得分:3)

问题在于您的错误行

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

错过>;它应该读

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

你正在尝试执行减法,因此会遇到如此奇怪的编译错误;将指针pWrapper视为整数,并从中减去调用ExecuteThread()(产生int)返回的值。但是,ExecuteThread()既不是全局函数也不是静态成员函数 - 因此编译器会抱怨。

答案 1 :(得分:2)

你错过了&gt;在电话上。你想要return pWrapper->ExecuteThread();

答案 2 :(得分:0)

你错过了“&gt;” 这是

pWrapper->ExecuteThread()

pWrapper-ExecuteThread()

答案 3 :(得分:0)

您无法使用该语法调用静态成员函数。请尝试执行以下操作:

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

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