2011-03-02 130 views
1

我有一個模板函數,我希望返回T或變體的類型。我試圖做如下,然而編譯器抱怨它不能將'variant'轉換爲int(我用T = int使用這個函數)。返回特定類型的模板

我該如何實現這個功能,以便我可以返回變體或類型中包含的變體。

它是從一個向量結構中獲得的。

template <typename T> 
T find_attribute(const std::string& attribute, bool isVariant = false) 
{ 
    std::vector<boost::shared_ptr<node> >::iterator nodes_iter = _request->begin(); 

    for (; nodes_iter != _request->end(); nodes_iter++) 
    { 
     size_t sz = (*nodes_iter)->attributes.size(); 
     std::vector<node::attrib>::iterator att_iter = (*nodes_iter)->attributes.begin(); 
     for (; att_iter != (*nodes_iter)->attributes.end(); att_iter++) 
     { 
      if (att_iter->key.compare(attribute) == 0) 
      { 
       if (isVariant) 
       { 
        return att_iter->value; //return variant 
       } 
       else 
       { 
        return boost::get<T>(att_iter->value); // return type inside variant as given by T. 
       } 
      } 
     } 
    } 
} 

回答

2

您可以爲find_attribute<boost::variant>(const std::string& attribute)創建模板專門化,返回變體和正常版本attribute<T>(const std::string& attribute)

普通版本會做:

return boost::get<T>(find_attribute<variant>(attribute)); 

但reme​​ber該模板在編譯時評價過!

如果find_attribute是一個成員函數,你可以使用這個MSVC編譯器。

如果你不能做模板專門化,你可以命名不同的功能。

+0

我會避免寫一個專門化,而是提供一個返回變體類型的非模板化版本。差異很小,但用戶代碼(請求變體類型時)會稍微更清晰(不需要在調用中添加'>',並且不需要以不同的方式命名該函數,因爲重載解析規則將選擇非模板版本。 – 2011-03-02 15:23:14

0

我應該如何實現這個,所以我可以只返回變體或類型包含的變種。

你不行。模板參數固定爲編譯時間,所以當你的程序發現它將不得不返回時,它已經很長時間了。

+0

所以對於變體我需要創建一個新的功能? – 2011-03-02 14:24:38

+0

在編譯時,你將不得不有某種方式來說明你想從這個函數中獲得什麼。這可能是調用函數模板的不同實例的一個大開關,但要返回的類型必須編碼到該開關中,並且在編譯之後設置好。 – sbi 2011-03-02 14:47:06