首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不计算std::conditional

不计算std::conditional
EN

Stack Overflow用户
提问于 2016-05-10 15:09:54
回答 2查看 300关注 0票数 1

请考虑以下几点:

代码语言:javascript
复制
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吐槽:

代码语言:javascript
复制
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。为什么会这样?如何修复这个小示例?

EN

回答 2

Stack Overflow用户

发布于 2016-05-10 15:14:50

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

代码语言:javascript
复制
template <bool flag> 
std::conditional_t<flag, int, double> 
f() { return 0; }

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

代码语言:javascript
复制
template <bool flag> 
typename std::conditional<flag, int, double>::type 
f() { return 0; }
票数 3
EN

Stack Overflow用户

发布于 2016-05-10 15:15:33

代码语言:javascript
复制
#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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37131572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档