给定一个lambda,是否可以找出它的参数类型和返回类型?如果有,怎么样?
基本上,我想要lambda_traits哪些可以用于以下方式:
auto lambda = [](int i) { return long(i*10); };
lambda_traits<decltype(lambda)>::param_type i; //i should be int
lambda_traits<decltype(lambda)>::return_type l; //l should be long
Run Code Online (Sandbox Code Playgroud)
背后的动机是我想lambda_traits在一个接受lambda作为参数的函数模板中使用,我需要知道它的参数类型和函数内部的返回类型:
template<typename TLambda>
void f(TLambda lambda)
{
typedef typename lambda_traits<TLambda>::param_type P;
typedef typename lambda_traits<TLambda>::return_type R;
std::function<R(P)> fun = lambda; //I want to do this!
//...
}
Run Code Online (Sandbox Code Playgroud)
目前,我们可以假设lambda只接受一个参数.
最初,我尝试使用std::function:
template<typename T>
A<T> f(std::function<bool(T)> fun)
{
return A<T>(fun);
}
f([](int){return true;}); //error
Run Code Online (Sandbox Code Playgroud)
但它显然会给出错误.所以我将其更改TLambda为函数模板的版本,并希望在函数std::function内部构造对象(如上所示).
我正在尝试做这样的事情(在c ++ 11中):
#include <utility>
template <typename T>
struct base {
using type = decltype( std::declval<T>().foo() );
};
struct bar : base<bar> {
int foo() { return 42;}
};
int main() {
bar::type x;
}
Run Code Online (Sandbox Code Playgroud)
失败与
prog.cc: In instantiation of 'struct base<bar>':
prog.cc:8:14: required from here
prog.cc:5:46: error: invalid use of incomplete type 'struct bar'
using type = decltype( std::declval<T>().foo() );
~~~~~~~~~~~~~~~~~~^~~
prog.cc:8:8: note: forward declaration of 'struct bar'
struct bar : base<bar> {
^~~
Run Code Online (Sandbox Code Playgroud)
如何声明bar::fooin 的返回类型的别名base …