给定一个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内部构造对象(如上所示).
我正在尝试创建一个可以使用带有0,1或2个参数的lambda调用的函数.由于我需要代码在g ++ 4.5和vs2010上工作(它不支持可变参数模板或lambda转换到函数指针),我想出的唯一想法是选择基于arity调用哪个实现.以下是我应该如何看待的非工作猜测.有没有办法修复我的代码或者有更好的方法来执行此操作?
#include <iostream>
#include <functional>
using namespace std;
template <class Func> struct arity;
template <class Func>
struct arity<Func()>{ static const int val = 0; };
template <class Func, class Arg1>
struct arity<Func(Arg1)>{ static const int val = 1; };
template <class Func, class Arg1, class Arg2>
struct arity<Func(Arg1,Arg2)>{ static const int val = 2; };
template<class F>
void bar(F f)
{
cout << arity<F>::val << endl;
}
int main()
{
bar([]{cout << "test" << endl;});
}
Run Code Online (Sandbox Code Playgroud) 有没有办法将c ++ 0x lambda的签名,结果和参数类型推断为Boost.MPL序列,例如boost::mpl::vector?例如,对于lambda
[]( float a, int b ) -> void { std::cout << a << b << std::endl; }
Run Code Online (Sandbox Code Playgroud)
我想得到一个boost::mpl::vector<void,float,int>.
Qt的QVariant类是否有任何现有(且方便)的访问者模式实现?
如果没有,是否有可能实现类似的东西boost::apply_visitor(),即最小化测试类型和铸造的重复?
我希望通过以下方式实现目标:
/* I have a QVariant that can contain anything, including user types */
QVariant variant;
/* But in my Visitor I'm interested only in ints and QStrings (for the sake of the example) */
struct Visitor
{
void operator()(int i) { /* do something with int */ }
void operator()(QString s) { /* ...or QString */ }
};
/* The question is: */
/* Can this be implemented in a generic way (without resorting to …Run Code Online (Sandbox Code Playgroud)