有没有办法让它更短更清晰?

时间:2015-12-12 21:08:54

标签: c++ stdmap

我们说这包括:

#include <map>
#include <boost/any.hpp>
#include <string>

代码:

int main()
{
    typedef std::map< std::string, boost::any > table;
    table foobar;
    foobar["foo"] = table();
    table* foobarfoo = boost::any_cast< table* >( foobar["foo"] );
    (*foobarfoo)["bar"] = int(5);
    int* test = boost::any_cast< int* >( (*foobarfoo)["bar"]);
}

虽然它看起来并不好看,但效果很好,特别是当我需要从一行map(int* test here)中取指针时。 我真的很想看到的是这样的:

int main()
{
    typedef std::map< std::string, boost::any > table;
    table foobar;
    foobar["foo"] = table();
    foobar["foo"]["bar"] = int(5);
    int* test = boost::any_cast< int* >( foobar["foo"]["bar"]);
}

这看起来更清楚,但它不会那样工作。我的问题是,有没有办法让第二个代码有点像一些小的修改,或者有一个替代方案看起来和第二个例子一样好并且仍然可以工作吗?

1 个答案:

答案 0 :(得分:0)

您可以将any对象转换为引用类型。

在这种情况下,最后一行有一个丑陋的双any_cast

int main()
{
    typedef std::map< std::string, boost::any > table;
    table foobar;
    foobar["foo"] = table();
    boost::any_cast< table& >( foobar["foo"] )["bar"] = int(5);
    int* test = boost::any_cast< int* >( &(boost::any_cast< table& >( foobar["foo"] )["bar"]));
}

你可以通过保存对第一次演员结果的引用来使它变得更漂亮:

int main()
{
    typedef std::map< std::string, boost::any > table;
    table foobar;
    foobar["foo"] = table();
    table& foo_table = boost::any_cast< table& >( foobar["foo"] );
    foo_table["bar"] = int(5);
    int* test = boost::any_cast< int* >( &(foo_table["bar"]) );
}

如果经常需要这种操作,你可以考虑更改外部地图的类型(如果没有,但table将存储在其中)或者创建一个看似{{1}的辅助函数}