通常的C++程序,函数的返回值是确定的类型,那么为什么需要通过invoke_result来声明函数的返回值类型呢?
用一个简单但不一定实际的例子进行说明:
#include <iostream>
using namespace std;int funcAdd(int a, int b)
{return a + b;
}int wrapFuncAdd(int a, int b)
{return funcAdd(a, b);
}int main()
{cout<<wrapFuncAdd(1, 2)<<endl;return 0;
}
这是一段平淡无奇的程序,但是假如有一天,funcAdd(也许是在另一个文件中定义的)被修改了类型为:
string funcAdd(int a, int b)
那么程序的编译将会报错。
可以通过invoke_result解决这个问题
#include <iostream>
#include <string>
#include <type_traits>
using namespace std;string funcAdd(int a, int b)
{return to_string(a + b);
}auto wrapFuncAdd(int a, int b) -> invoke_result<decltype(funcAdd), int, int>::type
{return funcAdd(a, b);
}int main()
{cout<<wrapFuncAdd(1, 2)<<endl;