C ++预处理生成变量成员,setter和映射

问题描述 投票:0回答:1

我正在尝试使用预处理器生成一些代码。在某些类中,我需要定义多个变量成员,它们相应的setter和一个包含每个已声明变量的引用的映射。

为了说明我的需求,您可以找到我想要实现的以下代码示例。在此示例中,我仅声明了两个变量,但实际上,应在不同的类中声明更多变量:

#include <boost/preprocessor.hpp>

#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>

class typeBase {
};

template <typename T>
class typeBase_: public typeBase {
    private:
        T value_;
    public:
        typeBase_() { }
        typeBase_(const T& v): value_(v) { }
};

using typeInt = typeBase_<int>;
using typeStr = typeBase_<std::string>;

std::unordered_set<std::string> changed_list_;

//////////////////////////////////////////////////////////
// Here use generation to generate the bellow code
//////////////////////////////////////////////////////////
typeInt mInt_;
typeStr mStr_;

std::unordered_map<std::string, typeBase&> properties_ = {
    {"mInt", mInt_},
    {"mStr", mStr_}
};

void set_mInt(const typeInt& mInt) {
    mInt_ = mInt;
    changed_list_.insert("mInt");
}

void set_mStr(const typeStr& mStr) {
    mStr_ = mStr;
    changed_list_.insert("mStr");
}
/////////////////////////////////////////////
/////////////////////////////////////////////

int main()
{
    set_mInt(2);
    set_mStr(std::string("test"));
}

[当我第一次尝试使用Boost预处理库时,我暂时无法创建包含对每个变量成员的引用的映射:

#define MODEL_DECLARE(...)                                                       \
  std::unordered_map<std::string, typeBase&> properties = {                      \
        MODEL_GENERATE_MAP_ITEMS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))          \
  };

#define MODEL_GENERATE_MAP_ITEMS(Args)                                           \
  BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(MODEL_GENERATE_MAP_ITEM, %%, Args))

#define MODEL_GENERATE_MAP_ITEM(s, Unused, Arg)                                  \
  {(MODEL_STRINGIFY(BOOST_PP_TUPLE_ELEM(2, 0, Arg)), BOOST_PP_TUPLE_ELEM(2, 0, Arg))}

#define MODEL_STRINGIFY_(V) #V
#define MODEL_STRINGIFY(V) MODEL_STRINGIFY_(V)

#define MODEL_MAKE_ITEM(s, Unused, Arg)                                          \
  {BOOST_PP_TUPLE_ELEM(2, 0, Arg) BOOST_PP_TUPLE_ELEM(2, 1, Arg)}

// Generate model with this line
MODEL_DECLARE((mInt, typeInt), (mStr, typeStr))

使用此代码,我产生了此预处理行:

std::unordered_map<std::string, typeBase&> properties = { {("mInt", mInt)}, {("mStr", mStr)} };

如您所见,我有括号需要删除,但我大胆未能做到。

您知道实现我所需的更好的解决方案,还是如何修复我的代码以成功生成所需的代码?

问候

EDIT1:

我开始实现@parktomatomi解决方案,并且我还尝试添加代码来声明变量和设置器:

#include <boost/preprocessor.hpp>

#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <cassert>

class typeBase {
};

template <typename T>
class typeBase_: public typeBase {
    private:
        T value_;
    public:
        typeBase_() { }
        typeBase_(const T& v): value_(v) { }
};

using typeInt = typeBase_<int>;
using typeStr = typeBase_<std::string>;

std::unordered_set<std::string> changed_list_;

//////////////////////////////////////////////////////////
// Here use generation to generate the bellow code
//////////////////////////////////////////////////////////   
template <typename... Ts>
std::unordered_map<std::string, typeBase*> build_properties(Ts&&... args) { 
    return std::unordered_map<std::string, typeBase*> { { args.first, args.second }... };
}

// Macro used to generate properties map
#define MODEL_GENERATE_MAP_ITEM(Name, Type)          std::make_pair( #Name, &Name##_ )
#define MODEL_UNWRAP_MAP_ITEM(Unused1, Unused2, Arg) MODEL_GENERATE_MAP_ITEM Arg
#define MODEL_GENERATE_MAP_ITEMS(Args)               BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(MODEL_UNWRAP_MAP_ITEM,,Args))

// Macro used to declare vars and setters
#define MODEL_GENERATE_VAR(Name, Type)              Type Name##_;                           \
                                                    void set_##Name(const Type& Name) {     \
                                                        Name##_ = Name;                     \
                                                        changed_list_.insert(#Name);        \
                                                    };
#define MODEL_UNWRAP_VAR(Unused1, Unused2, Arg)     MODEL_GENERATE_VAR Arg
#define MODEL_GENERATE_VARS(Args)                   BOOST_PP_SEQ_TRANSFORM(MODEL_UNWRAP_VAR,,Args)

// Macro to generate model
#define MODEL_DECLARE(...)                                                       \
  std::unordered_map<std::string, typeBase*> properties_ = build_properties(     \
        MODEL_GENERATE_MAP_ITEMS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))          \
  );                                                                             \
  MODEL_GENERATE_VARS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

// Generate model
MODEL_DECLARE((mInt, typeInt), (mStr, typeStr))

int main() {
    assert(properties_.size() == 2);
    assert(properties_["mInt"] == &mInt_);
    assert(properties_["mStr"] == &mStr_);
}

但是由于预处理生成会在声明周围加上括号,因此无法编译:

(typeInt mInt_; void set_mInt(const typeInt& mInt) { mInt_ = mInt; changed_list_.insert("mInt"); };) (typeStr mStr_; void set_mStr(const typeStr& mStr) { mStr_ = mStr; changed_list_.insert("mStr"); };)

如何删除该寄生虫?

c++ boost preprocessor variadic-macros
1个回答
0
投票

我遇到两个问题试图将其编译:

  1. 您没有参考容器
  2. 宏和括号don't mix well

要修复#1,请改用指针:

std::unordered_map<std::string, typeBase*>

要修复#2,请使用辅助函数初始化地图:

template <typename... Ts>
std::unordered_map<std::string, typeBase*> build_properties(Ts&&... args) { 
    return std::unordered_map<std::string, typeBase*> { { args.first, args.second }... };
}

然后目标变成了通过宏生成this

build_properties(
    std::make_pair("mInt", &mInt_),
    std::make_pair("mStr", &mStr_)
)

哪个更容易并且可以成功编译:

#define MODEL_GENERATE_MAP_ITEM(Name, Type) std::make_pair( #Name, &Name##_ )

#define MODEL_UNWRAP_MAP_ITEM(Unused1, Unused2, Arg) MODEL_GENERATE_MAP_ITEM Arg

#define MODEL_GENERATE_MAP_ITEMS(Args)                                           \
  BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(MODEL_UNWRAP_MAP_ITEM,,Args))

#define MODEL_DECLARE(...)                                                       \
  std::unordered_map<std::string, typeBase*> properties = build_properties(      \
        MODEL_GENERATE_MAP_ITEMS(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))          \
  );

// Generate model with this line
MODEL_DECLARE((mInt, typeInt), (mStr, typeStr))

与您的问题更直接相关的是,BOOST_PP_VARIADIC_TO_SEQ宏在您的参数周围添加了一对括号:

(mInt, typeInt), (mStr, typeStr) ==> ((mInt, typeInt)) ((mStr, typeStr))

因此BOOST_PP_SEQ_TRANSFORM生成其宏时,每个实例的参数都带有括号,例如(mInt, typeInt)。为了摆脱这些括号,我添加了此宏:

MODEL_UNWRAP_MAP_ITEM(Unused1, Unused2, Arg) MODEL_GENERATE_MAP_ITEM Arg

[Arg被替换时:

MODEL_GENERATE_MAP_ITEM (mInt, typeInt)

最后一次转换为:

std::make_pair( "mInt", mInt_ )

演示:https://godbolt.org/z/5fyo3N

© www.soinside.com 2019 - 2024. All rights reserved.