tags:

views:

224

answers:

4

I understand that the following code won't work, as i is a runtime parameter and not a compile time parameter. But i want to know, whether there is a way to achieve the same. i have a list of classes and i need to call a template function, with each of these classes.

void 
GucTable::refreshSessionParams()
{
    typedef  boost::mpl::vector< SessionXactDetails, SessionSchemaInfo  >   SessionParams;
    for( int i = 0; i < boost::mpl::size<SessionParams>::value; ++i )
        boost::mpl::at<SessionParams, i>::type* sparam = 
                        g_getSessionParam< boost::mpl::at<SessionParams, i>::type >();
        sparam->updateFromGucTable(this);
    } 
}

Can someone suggest me a easy and elegant way to perform the same? i need to iterate through the mpl::vector and use the type to call a global function and then use that parameter to do some run-time operations.

Thanks in advance, Gokul.

Working code

typedef  boost::mpl::vector< SessionXactDetails, SessionSchemaInfo  >   SessionParams;

class  GucSessionIterator
{
private:
    GucTable& m_table;

public:
    GucSessionIterator(GucTable& table)
        :m_table(table)
    {
    }

    template< typename U > void operator()(const U& )
    {
        g_getSessionParam<U>()->updateFromGucTable(m_table);
    }
};


void 
GucTable::refreshSessionParams()
{
    boost::mpl::for_each< SessionParams >( GucSessionIterator(*this) );
    return;
}
+3  A: 

I only used MPL for a collection of types for BOOST_AUTO_TEST_CASE_TEMPLATE, so my knowledge is quite limited. However, I'd guess you could use for_each to iterate through an MPL sequence.

doublep
Thanks. It worked.
Gokul
+2  A: 

You could make i a compile time constant and use template recursion to iterate through the classes.

the_drow
This also worked for me. Still wanted to follow the boost way of things. Thanks,
Gokul
Yeh same here but I don't know MPL at all. I used to be a Loki developer though :)
the_drow
A: 

Unfrotunately you will often find that the MPL is not really handy when it comes to cross-over from the compile time world to the runtime world.

There is a Boost library for this: Boost.Fusion, which purpose is exactly to mix metatemplate programming and runtime more easily.

If you read through the documentation, you'll realize that they don't shy from the MPL but rather build on it. The authors even acknowledge that their sequences aren't as efficient in compile-time operations that the MPL ones... thus the following guideline:

  • Compile-time computation: use the MPL
  • Need the sequence at runtime ? Once you computed it through the MPL, convert it to a Fusion one.
Matthieu M.