You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将使用std::invoke_result的C++17代码改为C++11兼容实现?

C++11下替换std::invoke_result的等效方案

原C++17代码用于获取std::chrono::system_clock::now()的返回类型:

using abc = std::chrono::system_clock;
using def = typename std::invoke_result<decltype(&abc::now)>::type;

你用std::result_of失败的核心原因是:C11的std::result_of要求模板参数为调用签名形式(即可调用类型(参数类型列表)),而C17的std::invoke_result是直接传入可调用类型和参数类型作为独立模板参数,两者的参数格式存在本质区别。

针对静态成员函数指针的场景,C++11下的等效代码如下:

#include <type_traits>
#include <chrono>

using abc = std::chrono::system_clock;
using def = typename std::result_of<decltype(&abc::now)()>::type;

关键说明

  • decltype(&abc::now)是静态成员函数的指针类型,std::result_of需要在其后添加(),以此表示该函数的调用参数列表(此处now是无参函数,所以用空括号)。
  • 必须包含<type_traits>头文件,std::result_of的定义位于该头文件中。
  • 这段代码会正确推导system_clock::now()的返回类型(即std::chrono::time_point<std::chrono::system_clock>)。

内容的提问来源于stack exchange,提问作者maero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:24:55