在C ++中模拟编译时反射

时间:2012-12-12 00:23:19

标签: c++ constexpr

我有以下结构:

struct Data
{
    std::string firstMember;
    std::string secondMember;
    std::string thirdMember;
};

我想以constexpr方式按字符串名称选择其中一个成员,例如

Data instance;
auto& member = getMember(instance, "firstMember"); 

getMember是constexpr函数/ struct / macros /有问题和表达式应该(我希望它)优化为简单auto& member = instance.firstMember;。我的愿望是能够从另一个getMember函数调用constexpr,而REGISTER_MEMBER(Data, "firstMember", firstMember); 函数又计算特定成员的名称 - >某种编译时间的反思。

我知道,C ++中没有任何反映,因此可以以某种方式注册(部分特殊化?使用一些宏魔法吗?)有问题的struct成员名称,如:

{{1}}

我想要的只是编译时优化并且在运行时什么都不做。这可能在C ++ 11中以及如何实现?

1 个答案:

答案 0 :(得分:13)

如评论中所述,首先看看BOOST_FUSION_ADAPT_STRUCT(和朋友):

#include <boost/fusion/include/adapt_struct.hpp>
#include <string>

struct Data
{
    std::string firstMember;
    std::string secondMember;
    std::string thirdMember;
};

BOOST_FUSION_ADAPT_STRUCT(
    Data,
    (std::string, firstMember)
    (std::string, secondMember)
    (std::string, thirdMember)
    )

这会将您的Data结构转换为Fusion可用的序列:

#include <boost/fusion/include/at_c.hpp>

int main()
{
    Data d = { "firstData", "secondData", "thirdData" };

    std::cout << boost::fusion::at_c<0>(d) << std::endl;
}

这会打印"firstData"。更改索引以按顺序引用成员。

在那里,我们现在可以使用数字在编译时引用成员。但你想要一个名字。在注释中还注意到,处理字符串是一个运行时特性......几乎。 C ++ 11为我们提供了constexpr

这有点棘手,但最终看起来像这样:

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/seq.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <stdexcept>

// and repeat for BOOST_FUSION_ADAPT_TPL_STRUCT, etc...
#define REFLECT_STRUCT(NAME, ATTRIBUTES)                                                \
        REFLECT_STRUCT_DETAIL(NAME,                                                     \
                              ATTRIBUTES,                                               \
                              BOOST_PP_SEQ_POP_FRONT(                                   \
                                BOOST_PP_CAT(                                           \
                                    /* warning: uses fusion implementation details: */  \
                                    BOOST_FUSION_ADAPT_STRUCT_FILLER_0(0,0)ATTRIBUTES,  \
                                    _END)))                                             \

#define REFLECT_STRUCT_DETAIL(NAME, ATTRIBUTES, WRAPPEDATTRIBUTES)                  \
        BOOST_FUSION_ADAPT_STRUCT(NAME, ATTRIBUTES)                                 \
                                                                                    \
        namespace detail                                                            \
        {                                                                           \
            namespace BOOST_PP_CAT(reflect_, NAME)                                  \
            {                                                                       \
                template <int N>                                                    \
                struct member_name;                                                 \
                                                                                    \
                BOOST_PP_SEQ_FOR_EACH_I(REFLECT_STRUCT_DETAIL_MEMBER_NAME,          \
                                        BOOST_PP_EMPTY,                             \
                                        WRAPPEDATTRIBUTES)                          \
                                                                                    \
                template <int N>                                                    \
                constexpr bool member_match_index(const std::size_t index,          \
                                                  const char* const str,            \
                                                  const std::size_t len)            \
                {                                                                   \
                    return index == len ||                                          \
                           (member_name<N>::value()[index] == str[index]            \
                            && member_match_index<N>(index + 1, str, len));         \
                }                                                                   \
                                                                                    \
                template <int N>                                                    \
                constexpr bool member_match(const char* const str,                  \
                                            const std::size_t len)                  \
                {                                                                   \
                    return len == member_name<N>::value_length                      \
                           && member_match_index<N>(0, str, len);                   \
                }                                                                   \
                                                                                    \
                constexpr int find_member(const char* const str,                    \
                                          const std::size_t len)                    \
                {                                                                   \
                    return BOOST_PP_REPEAT(BOOST_PP_SEQ_SIZE(WRAPPEDATTRIBUTES),    \
                                           REFLECT_STRUCT_DETAIL_MEMBER_NAME_TEST,  \
                                           BOOST_PP_EMPTY)                          \
                           throw std::runtime_error("could not find "               \
                                                    BOOST_PP_STRINGIZE(NAME)        \
                                                    " member");                     \
                }                                                                   \
            }                                                                       \
        }                                                                           \
                                                                                    \
        constexpr int BOOST_PP_CAT(indexof_, NAME)(const char* const str,           \
                                                   const std::size_t len)           \
        {                                                                           \
            return detail::BOOST_PP_CAT(reflect_, NAME)::find_member(str, len);     \
        }                                                                           \
                                                                                    \
        template <std::size_t N>                                                    \
        constexpr int BOOST_PP_CAT(indexof_, NAME)(const char (&str)[N])            \
        {                                                                           \
            return detail::BOOST_PP_CAT(reflect_, NAME)::find_member(&str[0], N);   \
        }

#define REFLECT_STRUCT_DETAIL_EXTRACT_NAME(pair) \
        BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(1, pair))

#define REFLECT_STRUCT_DETAIL_MEMBER_NAME(r, data, n, elem) \
        REFLECT_STRUCT_DETAIL_MEMBER_NAME_DETAIL(n, REFLECT_STRUCT_DETAIL_EXTRACT_NAME(elem))

#define REFLECT_STRUCT_DETAIL_MEMBER_NAME_DETAIL(n, name)               \
        template <>                                                     \
        struct member_name<n>                                           \
        {                                                               \
            static constexpr std::size_t value_length = sizeof(name);   \
            typedef const char value_type[value_length];                \
                                                                        \
            static constexpr const value_type& value()                  \
            {                                                           \
                return name;                                            \
            }                                                           \
        };

#define REFLECT_STRUCT_DETAIL_MEMBER_NAME_TEST(z, n, text) \
        member_match<n>(str, len) ? n :

它看起来很可怕,但如果你花时间把它拆开,它的可读性。

我们必须引入自己的宏来提供对成员名称的常量表达式访问;大多数丑陋来自处理Boost.Preprocessor列表。虽然Fusion也会在改编期间记录名称(请参阅boost::fusion::extension::struct_member_name),但它们未标记为constexpr,因此不幸对我们无法使用。

这给出了:

#include <boost/fusion/include/at_c.hpp>
#include <iostream>
#include <string>

struct Data
{
    std::string firstMember;
    std::string secondMember;
    std::string thirdMember;
};

REFLECT_STRUCT(
    Data,
    (std::string, firstMember)
    (std::string, secondMember)
    (std::string, thirdMember)
    )

// your desired code:
// (note the use of at_c ensures this is evaluated at comple-time)
#define GETMEMBER(data, member) boost::fusion::at_c<indexof_Data(member)>(data)

int main()
{
    Data d = { "firstData", "secondData", "thirdData" };

    std::cout << boost::fusion::at_c<indexof_Data("firstMember")>(d) << std::endl;
    std::cout << GETMEMBER(d, "secondMember") << std::endl;
    std::cout << GETMEMBER(d, "thirdMember") << std::endl;
    /* causes error: std::cout << GETMEMBER(d, "nonexistent_member") << std::endl; */
}

我认为这与你所追求的很接近。

但请记住,这可能并非都是必要的:Boost.Fusion可能已经拥有了你需要的东西。它位于纯编译时间(Boost.MPL)和常规运行时间之间的区域;适应你的结构,你已经可以做一些迭代(boost::fusion::for_each)。