检测函数对象(函子)和lambda特征
Detecting function object (functor) and lambda traits
如何检测null和一元函数指针、std::函数对象和函数(包括lambdas)的返回类型和参数类型?
Boost的功能特征和功能特征并不能让我开箱即用,但我愿意补充或取代它们。
我可以这样做:
namespace nsDetail
{
class Dummy { Dummy(); };
}
template<class Fn> struct FnTraits;
template<class R>
struct FnTraits<R(*)()>
{
typedef nsDetail::Dummy ParamType;
typedef R ReturnType;
typedef R Signature();
};
template<class R, class P>
struct FnTraits<R(*)(P)>
{
typedef P ParamType;
typedef R ReturnType;
typedef R Signature( P );
};
template<class R>
struct FnTraits< std::function<R()> >
{
typedef nsDetail::Dummy ParamType;
typedef R ReturnType;
typedef R Signature();
};
template<class R, class P>
struct FnTraits< std::function<R(P)> >
{
typedef P ParamType;
typedef R ReturnType;
typedef R Signature( P );
};
但是我应该如何专门处理函子/lambdas呢?
更新:也许这是对另一个问题的回答,但从重载转换为专业化?
在函子的一般情况下,即使用operator()
的类类型中,这是不可能的。这也包括lambda对象。考虑operator()
过载的情况:
struct functor {
double
operator()(double) const;
int
operator()(int) const;
};
typedef function_traits<functor>::result_type result_type;
result_type
应该是什么?
请注意,作为一种变通方法,一些协议(例如Boost.Variant中的boost::apply_visitor
)要求类中存在result_type
,并假设所有重载在接受不同类型时都返回与该result_type
兼容的类型。
当然,给定一些类型T0 ... Tn
,std::result_of<functor(T0, ..., Tn)>::type
给出了与参数类型相关联的返回类型。
在恰好存在operator()
的一个过载[1]的情况下,您可以获取operator()
成员并进行检查。
struct not_overloaded {
double
operator()(double) const;
};
template<typename T>
struct functor_traits {
typedef decltype(&T::operator()) type;
};
functor_traits<not_overloaded>::type
的类型为double (not_overloaded::*)(double) const
,只需付出一点努力,您就可以从中提取您想要的内容。(例如,形式Ret (T::*)(Args...) const
的专门化将与该类型相匹配。)
[1] :但函子也可以通过隐式转换为函数指针/引用来提供功能,因此您可能会错过
std::result_of
出了什么问题?
http://en.wikipedia.org/wiki/C%2B%2B0x#Uniform_method_for_computing_the_return_type_of_function_objects
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 特征命名访问向量段
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 将特征矩阵的向量设置为0
- 模板函数指针和lambda
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- Lambda 函数在特征中按元素方向
- 在 C++14 中使用通用 lambda 和自动返回类型特征获得不同的结果
- 检测函数对象(函子)和lambda特征
- 能够在lambda中使用未捕获的局部变量的编译时特征有什么意义?