2011-04-14 89 views
4

我需要反序列化其他對象提供的裝飾。與自動發電機相關的提升精神業力和提升變體「概念」

「裝飾」啓用的一件事是向量中的空條目。我在實際執行中遇到了一堵磚牆。不過,我已經設法收縮包裝它。代碼編譯:

#include <string> 
#include <boost/spirit/include/karma.hpp> 
#include <boost/variant.hpp> 
#include <boost/cstdint.hpp> 

namespace karma = boost::spirit::karma; 

typedef boost::variant<boost::int32_t, boost::int64_t> custom_variant; 

int main() 
{ 
    using karma::generate; 

    custom_variant v; 

    std::string temp; 

    std::back_insert_iterator<std::string> x(temp); 

    std::cout << v; 

    karma::generate(x, karma::auto_, v); 
} 

違規變化,試圖實現「未定義」類型,以及所需的概念。

#include <string> 
#include <boost/spirit/include/karma.hpp> 
#include <boost/variant.hpp> 
#include <boost/cstdint.hpp> 

namespace karma = boost::spirit::karma; 

struct undefined{}; 

std::ostream & operator<<(std::ostream & out, undefined const & undefined) 
{ 
    return out; 
} 

typedef boost::variant<undefined,boost::int32_t, boost::int64_t> custom_variant; 

int main() 
{ 
    using karma::generate; 

    custom_variant v; 

    std::string temp; 

    std::back_insert_iterator<std::string> x(temp); 

    std::cout << v; 

    karma::generate(x, karma::auto_, v); 
} 

如果我註釋掉karma::generate步驟,std::cout是有效的表達式(升壓::變體OutputStreamable)。 Spirit要求生成器的類型爲OutputStreamable(spirit :: karma OutputStreamable),並且上面的變體應該是OutputStreamable,因爲我已將undefined類型OutputStreamable設置爲no-op。

什麼給?使用帶有> 2級模板間接的庫時:(

我真的開始懷疑抵禦C++模板機制是值得的,也許我應該回去直-C

編輯1:

好吧,鏘給我一個合理的first錯誤...

error: no type named 'properties' in 'boost::spirit::karma::no_auto_mapping_exists'

現在我得弄清楚如何聯合國民主基金映射被認爲是無操作以獲得乾淨的轉換。這spirit documentation entry(和this特定)描述我需要看看。有沒有一種通用的未定義類型,是由精神提供的還是一種定義在提升中的類型,這種精神已經被映射爲無操作類型?

編輯2:

std::vector<boost::optional<boost::variant<..>>>開始看起來相當有吸引力的,因爲精神提供的類型,扣除他們。

回答

3

爲了這個目的,我建議使用spirit::unused_type,因爲它已經'知道'精神,它有一個operator<<()預定義(但任何其他類型都會這樣做) - 不是你真的需要該算子在第一個噶地點。

此外,還必須提供create_generator專業化(如你懷疑):

namespace boost { namespace spirit { namespace traits 
{ 
    template <> 
    struct create_generator<spirit::unused_type> 
    { 
     typedef spirit::karma::eps_type type; 

     static type call() 
     { 
      return spirit::karma::eps; 
     } 
    }; 
}}} 

將其映射到unused_typekarma::eps。這看起來正是你所需要的,因爲eps吃東西時不會產生任何東西,而總是成功。如果你走這條路線,你不需要使用optional<>

+0

謝謝,一如既往。因爲我有選擇,所以我會提供'undefined'的映射,因爲它已經在我的QI代碼中使用了,它讓我在我自己的界面背後有防火牆的精神:D我開始看到TMP擴展帶來的強大功能。只希望C++ 0x沒有放棄「概念」。 – 2011-04-15 10:55:45