不评估std :: conditional

时间:2016-05-10 07:09:54

标签: c++ c++11 typetraits

请考虑以下事项:

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抱怨:

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; }

看起来std::conditional未按照我的预期评估为int。为什么会出现这种情况?如何修复这个小例子?

2 个答案:

答案 0 :(得分:3)

您正在尝试返回std::conditional<...>的实例,而不是评估结果的类型,该实例以type成员类型保存。要检索计算类型,您可以使用std::conditional_t

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

std::conditional_t是C ++ 14,所以如果你坚持使用C ++ 11,你可以这样做:

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

答案 1 :(得分: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