c++ - cpp 函数,根据模板类型返回值
问题描述
我想将以下伪代码转换为 c++17 代码:
template<class T>
char* foo(){
if(T is a float) return "we have a float"
if(T is a int) return "we have a int"
if(T is a double) return "we have a double"
return "unknown"
}
这样我就可以像使用它一样
LOGD("%s", foo<float>());
LOGD("%s" foo<double>());
那可能吗 ?
解决方案
您可以使用std::is_same
来检查类型,并且由于您提到了 C++17,因此您可以使用constexpr if,它在编译时检查条件,并根据结果将丢弃语句真/假。
template<class T>
const char* foo(){
if constexpr (std::is_same_v<T, float>) return "we have a float";
else if constexpr (std::is_same_v<T, int>) return "we have a int";
else if constexpr (std::is_same_v<T, double>) return "we have a double";
else return "unknown";
}
在 C++17 之前,您还可以使用原始版本 if
,并且将在运行时检查条件。
顺便说一句:c 风格的字符串文字的类型为const char[]
,自 C++11 以来无法转换char*
,因此最好将返回类型更改为const char*
.
推荐阅读
- reactjs - 在 onClick 事件之后 UseState 不会重新呈现页面
- r - 将函数应用于具有多列的多列
- angular - 在 Angular 7 中可以使用什么来代替 $sce?
- ios - UITableView 仅加载在设备上可见的自定义单元格,并在添加更多单元格时崩溃
- node.js - 如何过滤使用复选框保存的 mongodb 文档?
- c# - 向 Teams 发送消息时出现未知错误
- angularjs - 在模板中分解我的代码后,当前日期未显示
- codeigniter - ajax 没有向控制器发送数据
- excel - 计算符合 1 个条件的日期之间的唯一文本值
- javascript - foreach 循环,使下一个输入字段成为必需