2016-12-08 56 views
1

鑑於struct outer { struct inner { }; }演繹外類型,我想從具有內類型的參數推斷外類型:從內部類型參數

template <typename T> 
void f(T t) { ... } 

f(outer::inner p) 
{ 
    // deduce typename 'outer' here 
} 

假設所有感興趣的outer具有內部命名inner

+1

這解決它:http://stackoverflow.com/q/ 24206337/1774667? – Yakk

+0

@Yakk,我不擁有參數類型;我無法檢測它們。 – ThomasMcLeod

回答

3

作爲替代方案,您可以創建你手動送入性狀:

template <typename T> struct outer_type; 

template <> struct outer_type<outer::inner> { using type = outer; }; 
// ... other specialization for each outer::inner types 

然後:

template <typename T> 
void f(T t) 
{ 
    using outer = typename outer_type<T>::type; 
    // ... 
} 
+0

可能可以通過枚舉外部類型來實現。在'tag '上重載'()'創建一個類型,以便將'tag '和'...'返回到'tag '或其他。 then'result_of_t )>'從'T = outer :: inner'獲取'tag ',並提取標籤內的類型。 – Yakk

2

不,對不起,模板參數扣除將無法爲您做到這一點。

您應該在inner中包含一個到outer類型的typedef。

struct outer { 
    struct inner { 
     using OuterType = outer; 
    }; 
}; 

template <typename inner> 
void f(inner x) { 
    typedef typename inner::OuterType outer; 
    // ... 
} 
+0

我明白這是如何工作的,但我無法訪問此參數以便像這樣測試它。 – ThomasMcLeod

+0

@ThomasMcLeod我認爲你應該接受另一個答案,然後 – Brian