When binding constructor getting an error: missing 'typename' prior to dependent type name in C++

When binding constructor getting an error: missing 'typename' prior to dependent type name in C++

如何在 C++ 中绑定构造函数?

在一个 class 中,我有模板 class,其构造函数如下所示:

namespace EMRProcess
{
template<typename T>
    class CEMRImpl
    {

CEMRImpl(EMRProcessSR::CWebHandler<T>*  pHandler_, 
                            CSocketRemover* pSocketRemover, const std::string& strID, const std::string& strNo);

};
}

来自另一个 class,我正在尝试如下所示绑定构造函数:

m_pMyObj->processEvent(EVT_MED, strTestId,
                                           std::bind(&EMRProcess::CEMRImpl<T>::CEMRImpl,
                                                     this,
                                                     this,
                                                     strID,
                                                     strNo));

编译时出现错误:在相关类型名称 'EMRProcess::CEMRImpl::CEMRImpl'

之前缺少 'typename'

有人可以帮我解决这个问题吗?

您可以实现创建实例的静态成员函数:

static auto create(
        CWebHandler<T>* pHandler, 
        CSocketRemover* pSocketRemover, 
        const std::string& strId, 
        const std::string& strNo) 
{
    return CEMRImpl<T>(pHandler, pSocketRemover, strId, strNo);
}

基于此,您可以使用 bind 创建可调用对象:

static auto createFactory(
        CWebHandler<T>* pHandler, 
        CSocketRemover* pSocketRemover, 
        const std::string& strId, 
        const std::string& strNo) 
{
    return std::bind(create, pHandler, pSocketRemover, strId, strNo);
}

或者您可以只使用 Remy Lebeau 提到的 lambda:

auto task_factory = [] { return EMRProcessSR::CEMRImpl<int>(pHandler, pSocketRemover, "foo", "bar");};

您尝试使用 std:::bind() 构造函数所做的事情永远不会按原样工作,因为它非法 获取构造函数的地址。但是 lambda 可以在任何可以使用 std::bind() 的地方使用(事实上,lambda 几乎总是比 std::bind() 更受欢迎),所以让 lambda 正常调用构造函数并 return 新的对象,例如:

m_pMyObj->processEvent(EVT_MED, strTestId,
    [&, this](){ return EMRProcess::CEMRImpl<T>(this, this, strID, strNo); }
);