2009-09-11 108 views

回答

1

您可以編寫一個簡單的代碼生成器,該代碼生成器用映射發出頭文件,並將其作爲構建過程中的預構建步驟運行。

1

您正在尋找Boost.Assign's map_list_of。它也適用於hashmaps。

#include <boost/assign/list_of.hpp> // for 'map_list_of()' 
#include <boost/assert.hpp> 
#include <map> 
using namespace std; 
using namespace boost::assign; // bring 'map_list_of()' into scope 

{ 
    map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); 
    BOOST_ASSERT(next.size() == 5); 
    BOOST_ASSERT(next[ 1 ] == 2); 
    BOOST_ASSERT(next[ 5 ] == 6); 

    // or we can use 'list_of()' by specifying what type 
    // the list consists of 
    next = list_of< pair<int,int> >(6,7)(7,8)(8,9); 
    BOOST_ASSERT(next.size() == 3); 
    BOOST_ASSERT(next[ 6 ] == 7); 
    BOOST_ASSERT(next[ 8 ] == 9); 
} 
+2

在此示例中,該映射仍在運行時生成。它看起來像是同樣的操作的syniac糖。 – bradtgmurray 2011-03-21 16:18:37