如何在不指定参数列表的情况下获取函数定义的返回类型?
获取无参数列表的函数返回类型方案
你可以通过模板特化的方式提取函数的返回类型,无需知晓参数列表的具体信息,完全避开std::invoke_result需要参数的限制。核心思路是利用模板匹配不同类型的函数签名,直接剥离出返回类型部分。
实现代码
#include <type_traits> // 通用模板框架 template<typename Func> struct function_return_type; // 特化:匹配普通函数、函数指针 template<typename Ret, typename... Args> struct function_return_type<Ret(Args...)> { using type = Ret; }; // 特化:匹配非const成员函数 template<typename Ret, typename Class, typename... Args> struct function_return_type<Ret(Class::*)(Args...)> { using type = Ret; }; // 特化:匹配const成员函数 template<typename Ret, typename Class, typename... Args> struct function_return_type<Ret(Class::*)(Args...) const> { using type = Ret; }; // 简化使用的类型别名 template<typename Func> using function_return_type_t = typename function_return_type<Func>::type; // 测试示例 int sample_func(int, bool) { return 0; } struct DemoClass { double get_value() const { return 3.14; } }; int main() { // 验证普通函数返回类型 static_assert(std::is_same_v<function_return_type_t<decltype(sample_func)>, int>); // 验证const成员函数返回类型 static_assert(std::is_same_v<function_return_type_t<decltype(&DemoClass::get_value)>, double>); return 0; }
说明
- 这套模板会匹配普通函数、函数指针、非const成员函数、const成员函数等常见的函数类型,直接提取返回类型
Ret,完全忽略参数列表Args...的内容。 - 使用时只需要通过
decltype获取函数的类型,传入function_return_type_t即可得到返回类型,不需要任何参数信息。
内容的提问来源于stack exchange,提问作者Илья Коваленко
相关产品推荐
相关产品推荐

