2016-05-10 4 views
1

Betrachten Sie das folgende:std :: bedingte wird nicht ausgewertet

template <bool flag> std::conditional<flag, int, double> f() { return 0; } 

void g(int a); 

int main() { 
    g(f<true>()); 
    return 0; 
} 

gcc 4.8.2 klagt:

temp.cpp:18:16: error: cannot convert ‘std::conditional<true, int, double>’ to ‘int’ for argument ‘1’ to ‘void g(int)’ 
    g(f<true>()); 
       ^
temp.cpp: In instantiation of ‘std::conditional<flag, int, double> f() [with bool flag = true]’: 
temp.cpp:18:15: required from here 
temp.cpp:13:71: error: could not convert ‘0’ from ‘int’ to ‘std::conditional<true, int, double>’ 
template <bool flag> std::conditional<flag, int, double> f() { return 0; } 

Es sieht aus wie std::conditional wird int nicht bewertet, wie ich erwarten würde. Warum ist das der Fall und wie kann dieses kleine Beispiel behoben werden?

+1

Warum erwarten Sie, dass es zu "int" ausgewertet wird? War es etwas in der Dokumentation? – juanchopanza

+0

'template struct konditional;' Die Dokumentation besagt: "Stellt den Typ member typedef bereit, der als' T' definiert ist, wenn 'B' zur Kompilierzeit' true' ist oder als 'F 'wenn' B '' falsch 'ist. " In unserem Fall ist "B" "wahr" und "T" ist "int". – AlwaysLearning

+1

Aber es heißt nicht, dass ein 'std :: conditional ' zu 'int' auswertet. Der Hinweis ist in der "member typedef". – juanchopanza

Antwort

3

Sie versuchen, eine Instanz von std::conditional<...> zurückzugeben, nicht den Typ, der sich aus der Auswertung ergibt und der in einem type Mitgliedstyp gespeichert ist. Um den berechneten Typ abrufen könnten Sie std::conditional_t verwenden:

template <bool flag> 
std::conditional_t<flag, int, double> 
f() { return 0; } 

std::conditional_t ist C++ 14, also wenn Sie mit C stecken ++ 11 können Sie dies tun, anstatt:

template <bool flag> 
typename std::conditional<flag, int, double>::type 
f() { return 0; } 
0
#include "iostream" 
template <bool flag> typename std::conditional<flag, int, double>::type f() { return 0; } 

void g(int a); 

int main() { 
    g(f<true>()); 
    return 0; 
} 

https://godbolt.org/g/lf52TO