2016-11-04 66 views
1

我想從列表中找到我可以用模板參數構造的類型。在這個例子中:std :: is_constructible在列表中

using my_type = typename get_constructible<char *, int, std::string>::type; 

my_type必須std::string因爲在列表std::string是可以與一個char *來構造所述第一。

我嘗試這樣做:

#include <string> 
#include <utility> 

template<typename T, typename... Rest> 
struct get_constructible 
{ 
    using type = void; 
}; 

template<typename T, typename First, typename... Rest> 
struct get_constructible<T, First, Rest...> 
{ 
    using type = typename std::conditional< 
    std::is_constructible<First, T>::value, 
    First, 
    get_constructible<T, Rest...>::type 
    >::type; 
}; 

int main(void) 
{ 
    using my_type = get_constructible<char *, int, std::string>::type; 
    my_type s("Hi!"); 
} 

我不明白的地方我的邏輯失敗。

回答

7

你的邏輯看起來不錯,但你錯過的從屬名稱get_constructible<T, Rest...>::type一個typename

using type = typename std::conditional< 
    std::is_constructible<First, T>::value, 
    First, 
    typename get_constructible<T, Rest...>::type 
//^^^^^^^^ 
>::type; 
+4

鐺錯誤:「錯誤:模板類型參數模板參數必須是一個類型的,**你忘了'typename'?**「 – bolov

+0

@bolov是的,GCC的錯誤沒有多大幫助。 – TartanLlama

+1

這就是爲什麼我不能很快地理解錯誤時使用gcc和clang進行編譯的原因。其中一個可以握住我的手,就像這個例子。 – bolov