Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a particular template function based on an enumerated value

Tags:

c++

templates

Consider the following code where in I am calling a specific template function computecost depending on an enumerated value (category). In call cases the arguments of computecost are identical. There exists a one-one correspondence between the enum values and the C++ types. As the arguments to computecost are always identical across all the calls, is it possible to write the following code more compactly, ie. without repeating for every type/enum value.

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;
    }
like image 620
suresh Avatar asked Sep 09 '11 03:09

suresh


1 Answers

You could have a function that takes category and returns an appropriate function pointer, which is then called with the appropriate arguments:

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);

Or using a map, as Mark suggested:

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);
like image 155
Hugh Avatar answered Sep 27 '22 22:09

Hugh