为静态转换索引数组创建数组

时间:2014-09-11 05:58:55

标签: c++ arrays static-cast

我不知道我的标题是否正确,但我试图消除重复,所以我认为我应该将这些定义放在一个数组中。有人可以建议我如何把pButton放在数组中吗?我在想像pButton [EButtonHost],pButton [EButtonUsername]等。

#define pButtonHost static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonHost])
#define pButtonUsername static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonUsername])
#define pButtonPassword static_cast<XQtMultipleStringInputButton*>(m_pButtonList[EButtonPassword])

我有一个像这样的方法。

XIniFile readIniFile;
readIniFile.open(k_systemIniFile, EIniReadOnly);

string data;

readIniFile.readString("Server", "host", data);
pButtonHost->setString(data);
m_host = pButtonHost->getString();

readIniFile.readString("Server", "username", data);
pButtonUsername->setString(data);
m_username = pButtonUsername->getString();

readIniFile.readString("Server", "password", data);
pButtonPassword->setString(data);
m_password = pButtonPassword->getString();

它们看起来像重复,所以我试图优化它。谢谢!

更新: 我现在有类似的东西。这是对的吗?或者你有更好的建议吗?

for (int i = 0; i < 3; ++i) {
    readIniFile.readString("Server", k_dataList[i], data);
    static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->setString(data);
    m_pData[i] = static_cast<XQtMultipleStringInputButton*>(m_pButtonList[i])->getString();
}

2 个答案:

答案 0 :(得分:2)

使用auto和`lambda&#39;,

,下面的代码看起来很清晰
auto GetConfigInfo = [&](string section_name, ButtonType btn_type)-> string
{
    readIniFile.readString("Server", section_name, data);
    m_pButtonList[btn_type_]->setString(data);
    return m_pButtonList->getString();
};

m_host      = GetConfigInfo("host",     EButtonHost);
m_username  = GetConfigInfo("username", EButtonUserName);
m_password  = GetConfigInfo("password", EButtonPassword);

和使用struct的定义数据类型可以是其他方法。

struct ConfigDefine
{
    string  section_;
    ButtonType btn_type_; //your enum button type, such as EButtonHost, EButtonUserName
    string& result_;

}configs[]  = 
{
    {"host",     EButtonHost,     m_host},
    {"username", EButtonUserName, m_username},
    {"password", EButtonPassword, m_password}
};

for_each(std::begin(configs), std::end(configs), [&](ConfigDefine& config)
{
    readIniFile.readString("Server", config.section_, data);
    m_pButtonList[config.btn_type_]->setString(data);
    config.result_ = pButtonHost->getString();

});

答案 1 :(得分:1)

你打算有这样的东西吗?

#define ASIZE 3
int indx[ASIZE] = {EButtonHost, EButtonUsername, EButtonPassword};
string s[ASIZE] = {"host", "username", "password"};
string *m[ASIZE] = {&m_host, &m_username, &m_password};

for (int i = 0; i < ASIZE; i++) {
  readIniFile.readString("Server", s[i].c_str(), data);
  pButtonHost->setString(data);
  *m[i] = pButtonHost->getString();
}