请考虑以下几点:
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。为什么会这样?如何修复这个小示例?
发布于 2016-05-10 15:14:50
您正在尝试返回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; }发布于 2016-05-10 15:15:33
#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://stackoverflow.com/questions/37131572
复制相似问题