Gokul
Gokul

Reputation: 933

C++ boost mpl vector

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

Upvotes: 1

Views: 5046

Answers (3)

Matthieu M.
Matthieu M.

Reputation: 299740

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.

Upvotes: 1

the_drow
the_drow

Reputation: 19181

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

Upvotes: 3

user319799
user319799

Reputation:

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.

Upvotes: 3

Related Questions