通过自定义宏构造boost :: fusion :: map(以及更多)

时间:2014-08-11 08:32:52

标签: c++ templates boost boost-preprocessor

我有一个traits类,其中包含每个类在boost :: fusion :: map中的所有信号。

示例:

template <typename T> struct EventTraits;

class SomeClass;

template <> struct EventTraits<SomeClass>
{
    struct Started;
    struct Finished;
    typedef boost::fusion::map<
        boost::fusion::pair<Started, boost::signals2::signal<void()>>,
        boost::fusion::pair<Finished, boost::signals2::signal<void(int)>>
    > Events;
};

由于我经常需要这种特性专业化,我想有一个宏可以为我节省一些打字,就像这个想象中的例子:

CONSTRUCT_EVENTS(
    SomeClass,
    (Started, void())
    (Finished, void(int))
)

我怎样才能实现这样的CONSTRUCT_EVENTS宏? 作为一个起点,我看了BOOST_FUSION_ADAPT_STRUCT,然后看了Boost预处理器,但我还没有使用后者,所以我希望有人可以指导我。

1 个答案:

答案 0 :(得分:2)

这是应该有用的东西:

#include <boost/fusion/container/map.hpp>
#include <boost/preprocessor.hpp>
#include <boost/signals2.hpp>

template <typename T> struct EventTraits;

#define DECLARE_EVENT_STRUCT(r, data, elem) struct BOOST_PP_TUPLE_ELEM(2,0,elem);
#define DECLARE_MAP_ITEM(r, data, i, elem) BOOST_PP_COMMA_IF(i) boost::fusion::pair<BOOST_PP_TUPLE_ELEM(2,0,elem), boost::signals2::signal<BOOST_PP_TUPLE_ELEM(2,1,elem)> >
#define CONSTRUCT_EVENTS_(Name, EventSeq)                          \
    class Name;                                                    \
    template <> struct EventTraits<Name>                           \
    {                                                              \
        BOOST_PP_SEQ_FOR_EACH(DECLARE_EVENT_STRUCT, _, EventSeq)   \
        typedef boost::fusion::map                                 \
        <                                                          \
            BOOST_PP_SEQ_FOR_EACH_I(DECLARE_MAP_ITEM, _, EventSeq) \
        > Events;                                                  \
    };                                                             \
/***/

//! Stuff to transform (A,B)(C,D) into ((A,B))((C,D)) so BOOST_PP_SEQ_FOR_EACH can be used. (sequence of tuples)
#define ADD_PAREN_1(A, B) ((A, B)) ADD_PAREN_2 
#define ADD_PAREN_2(A, B) ((A, B)) ADD_PAREN_1 
#define ADD_PAREN_1_END 
#define ADD_PAREN_2_END 
#define CONSTRUCT_EVENT(Name, EventSeq)                            \
CONSTRUCT_EVENTS_(Name, BOOST_PP_CAT(ADD_PAREN_1 EventSeq,_END))   \
/***/

//! Check the output (I use this on visual studio)
#pragma  message(BOOST_PP_STRINGIZE((CONSTRUCT_EVENT(SomeClass, (Started, void())(Finished, void(int))))))

//! Result (with formatting applied)
class SomeClass; 
template <> 
struct EventTraits<SomeClass> 
{
    struct Started; 
    struct Finished; 
    typedef boost::fusion::map 
        <
            boost::fusion::pair<Started, boost::signals2::signal<void()> >
          , boost::fusion::pair<Finished, boost::signals2::signal<void(int)> >
        > Events; 
};

int main()
{
    return 0;
}