从函数模板类型中提取返回类型
Extracting return type from function template type
我有一个类似于以下内容的包装函数:
template<typename Func, typename ... Args>
void func(Func f, Args ... args) {
...
f(args...);
...
}
是否可以在编译时从类型Func
中提取返回类型?
例如,用户具有代码并按以下方式调用func
:
template<typename T>
T add(const T& l, const T& r) {
return l + r;
}
int main(int argc, char** argv) {
double a = 4.5, b = 5.5;
func(add<double>, a, b);
return 0;
}
我们可以在调用func
时推断出一个返回double
的函数被传递给它吗?我想将返回类型信息用于func
中的其他内容。
以下任一方法都可以
using result_type = decltype(std::declval<Func>()(std::declval<Args>()...));
或
using result_type = typename std::result_of<Func(Args...)>::type;
现场演示
由于 c++17 std::invoke_result
:
using result_type = typename std::invoke_result_t<Func(Args...)>;
如果你可以访问C++14,或者只是出于好奇,尽量不要提交到特定的类型。以下代码使用泛型 lambda,并为您推断类型。在许多情况下,我发现使用起来要容易得多。
#include <iostream>
using namespace std;
template<typename Func, typename ... Args>
void func(Func&& f, Args ... args) {
return;
}
auto add = [](auto l, auto r) { return l * r; };
int main()
{
auto a = double{4.5};
auto b = double{5.5};
func(add, a, b);
return 0;
}
Ideone:http://ideone.com/wXnc0g
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 制作解析器以提取函数名称、参数、返回类型
- 提取函数指针参数和返回类型
- 从函数模板类型中提取返回类型
- 接受lambda作为函数参数并提取返回类型
- 从重载函数中提取返回类型
- 从转换运算符到函数指针提取返回类型和参数类型