2016-11-11 39 views
1

我需要創建一個存儲多個用戶定義類型的類。它應該根據需要返回其中的一個。有沒有辦法實現一個函數來返回所有類型?根據請求存儲多種類型並返回單一類型

請注意:我無法使用Boost庫。我需要在Visual Studio中實現

class One {}; 
class Two {}; 
class Three {}; 

enum Type 
{ 
    OneType, 
    TwoType, 
    ThreeType 
}; 
class GenericType 
{ 
    template <typename T> // --- How to implement this function 
    T getValue(Type type) 
    { 
    switch(type) 
    { 
     case One: return oneType; // Error 
     case Two: return twoType; 
     case Three: return threeType; 
    } 
    } 
    shared_ptr<OneType> oneType; 
    shared_ptr<TwoType> twoType; 
    shared_ptr<ThreeType> threeType; 
    Type m_type; 
}; 

回答

1

在C++ 11中,您有一個執行此任務的std::tuple類。你可以用std::get檢索所需的元素,像這樣:

// Create a tuple 
std::tuple<std::shared_ptr<OneType>, std::shared_ptr<TwoType>> tuple{null, null}; 
// Get element 
std::get<std::shared_ptr<OneType>>(tuple) 
+0

std :: get()只能獲取索引的項目(作爲參數提供) – Neo

1

此聲明,

template <typename T> // --- How to implement this function 
T getValue(Type type) 

&hellip;其中Typeenum,它使參數的運行時間選擇決定了函數結果類型的編譯時間選擇,或者需要參數值的運行時選擇與類型的編譯時間選擇兼容。

前者在時間上落後,所以沒有打開,後者只是愚蠢的。

如果一個普通的函數模板適合您,那麼解決方案很簡單:針對每種相關類型進行專門化。

如果您需要運行時間選擇,那麼應該使用通用的結果包裝類型。對於價值語義,它可以是具有union成員的類,即歧視聯盟。對於引用語義,它可以是指向可能的結果類型的公共基類的指針。

+0

對不起,我無法完全理解它。常見的結果包裝類型是什麼意思?你的意思是std :: tuple? – Neo

+0

@Neo:那會是'boost :: variant'。既然你不能使用Boost,你必須自己動手。因此實施建議。 'std :: tuple'不是任何東西的解決方案,因爲它只是暴露成員:如果你可以公開成員並且對於客戶端代碼來說足夠了,那麼就沒有任何問題需要解決。 –