基于枚举值调用特定模板函数

sur*_*esh 5 c++ templates

请考虑以下代码,其中我computecost根据枚举值(类别)调用特定模板函数.在调用案例中,参数computecost是相同的.枚举值和C++类型之间存在一对一的对应关系.由于参数computecost在所有调用中始终相同,因此可以更紧凑地编写以下代码,即.不重复每个类型/枚举值.

mxClassID category = mxGetClassID(prhs);
    switch (category)  {
     case mxINT8_CLASS:   computecost<signed char>(T,offT,Offset,CostMatrix);   break;
     case mxUINT8_CLASS:  computecost<unsigned char>(T,offT,Offset,CostMatrix);  break;
     case mxINT16_CLASS:  computecost<signed short>(T,offT,Offset,CostMatrix);  break;
     case mxUINT16_CLASS: computecost<unsigned short>(T,offT,Offset,CostMatrix); break;
     case mxINT32_CLASS:  computecost<signed int>(T,offT,Offset,CostMatrix);  break;
     case mxSINGLE_CLASS: computecost<float>(T,offT,Offset,CostMatrix); break;
     case mxDOUBLE_CLASS: computecost<double>(T,offT,Offset,CostMatrix); break;
     default: break;
    }
Run Code Online (Sandbox Code Playgroud)

Hug*_*ugh 5

您可以有一个函数,它接受category并返回适当的函数指针,然后使用适当的参数调用该指针:

decltype(&computecost<int>) cost_computer(mxClassID const category) {
    switch (category) {
        case mxINT8_CLASS: return &computecost<signed char>;
        ...
    }
}

cost_computer(mxGetClassID(prhs))(T, offT, Offset, CostMatrix);
Run Code Online (Sandbox Code Playgroud)

或者使用map,如马克建议的:

std::map<mxClassID, decltype(&computecost<int>)> compute_functions =
    boost::assign::map_list_of
        (mxINT8_CLASS, &computecost<signed char>)
        // ... and so on
compute_functions[mxGetClassID(prhs)](T, offT, Offset, CostMatrix);
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 1

由于编译器将每个模板化函数视为不同的函数,因此无法避免对每个模板化函数进行不同的调用。您可以通过创建函数指针表来简化,因为每个函数都具有相同的签名。