c++ - C++ 编译代码取决于 auto 的具体类型
问题描述
我有一段 C++ 代码
auto returnvalue = m_func(x, y, z);
其中 m_func 的类型取决于模板参数。之后我处理returnvalue
哪个工作正常,直到m_func
一个函数返回 void。但我需要一种机制来调用
m_func(x,y,z)
如果 m_func 的返回值为 void 而上述版本不是。总的来说,在伪代码中它需要看起来像
if ( returnvalue of m_func is void )
call m_func directly
else
auto retval = m_func(...)
handle the return value
这些如何用 C++11/14 完成?
编辑:
m_func 是:
void func(type1 arg1, type2 arg, ...)
或者
std::tuple<...> func(type1 arg1, type2 arg, ...)
解决方案
在 C++17 之前,您可以使用模板特化:
template<class R>
struct handle {
template<class F>
static void the_return_value(F m_func) {
auto retval = m_func(x, y, z);
// handle the return value
}
};
template<>
struct handle<void> {
template<class F>
static void the_return_value(F m_func) {
m_func(x, y, z);
}
};
// usage
using R = decltype(m_func(x, y, z));
handle<R>::the_return_value(m_func);
在 C++17 中,您可以if constexpr
改用:
using R = decltype(m_func(x, y, z));
if constexpr (std::is_void_v<R>) {
m_func(x, y, z);
} else {
auto retval = m_func(x, y, z);
// handle the return value
}
推荐阅读
- r - 导入的 csv 文件在 R studio 中仍然是一个平面表
- python - 将嵌套列表中的日期字符串拆分为按月对列表进行分组 - Python
- gradle - Gradle 构建失败,安装 ml-gradle 插件
- php - 在 codeigniter 中使用 REST Api 时出现 CSRF 令牌错误
- azure - Azure Logs 中自定义指标的时间序列分解和绘图
- neural-network - Pytorch:从批处理加载检查点而不再次迭代数据集
- arrays - 尝试从 Soap WebService 发送大字节 [] 时出现 OutOfMemory 异常
- kotlin - 导航图某些片段后按不起作用
- node.js - 从主路由文件中调用 Node.js 模块函数
- php - 是否可以在电报机器人 api 中使用一条消息同时发送 ReplyKeybaordMarkup 和 InlineKeyboardmarkup