#include <iostream>
#include <type_traits>
using namespace std;
template< class Fun, class...Args >
auto fun(Fun&& f, Args&&...args) -> decltype(f(args...))
{
return f(std::forward<Args>(args)...);
}
template< class Fun, class...Args >
decltype((*(Fun*)0)((*(Args*)0)...)) funZero(Fun f, Args...args)
{
return f(args...);
}
template< class Fun, class...Args >
decltype(declval<Fun>()(declval<Args>()...)) funDeclval(Fun f, Args...args)
{
return f(args...);
}
template< class Fun, class...Args >
typename std::result_of<Fun(Args...)>::type funResult(Fun f, Args...args)
{
return f(args...);
}
template< class Fun, class...Args >
typename std::result_of<Fun && (Args&&...)>::type
funResultR(Fun&&f, Args&&...args)
{
return f(std::forward<Args>(args)...);
}
int funTest(int a)
{
return a;
}
int main()
{
int a = fun(funTest, 1);
int b = funZero(funTest, 2);
int c = funDeclval(funTest, 3);
int d = funResult(funTest, 4);
int e = funResultR(funTest, 5);
std::result_of<decltype(funTest)&(int)>::type x;
return 0;
}
演变过程
template< class Fun, class…Args >
auto fun(Fun&& f, Args&&…args) -> decltype(f(args…))
template< class Fun, class…Args >
decltype(((Fun)0)(((Args)0)…)) funZero(Fun f, Args…args)
template< class Fun, class…Args >
decltype(declval()(declval()…)) funDeclval(Fun f, Args…args)
template< class Fun, class…Args >
typename std::result_of<Fun(Args…)>::type funResult(Fun f, Args…args)
result_of等价于decltype(declval()(declval()…))等价于decltype(((Fun)0)(((Args)0)…))
result_of只能用于可调用对象。
可调用对象:
- 函数指针
- 仿函数