成员函数特征
Member function traits
我正在编写一个封装成员函数以减少调用的模板类-如果某些条件为真,则不需要调用成员函数。签名看起来像这样
template <typename MemFuncType, MemFuncType> class MemberWrapper;
我可以这样专门化它:
template <typename R, typename T, R T::* MemFunc> class MemberWrapper<R T::*, MemFunc>{};
我还想限制R T::*
的参数数量。我该怎么做呢?
我能想到的唯一解决方案是通过提供基于返回类型、函数类型、参数列表和cv限定符的部分专门化来实现成员函数的trait类。这将导致像当前std::mem_fn
过载那样的繁琐实现。有没有更好的方法?
EDIT:将Ret
改为R
。正如在注释中指出的,它不是真正的返回类型,特殊化是无效的。
不要尝试将所有内容放入一个类中。成员函数是类的成员函数。因此,从创建一些函数特征类开始,例如
template< typename T >
class function_traits
{
static_assert( sizeof( T ) == 0,
"function_traits<T>: T is not a function type" );
};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) >
{
constexpr static const std::size_t arity = sizeof...( Ts );
using result_type = R;
};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) const > : function_traits< R( Ts... ) > {};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) & > : function_traits< R( Ts... ) > {};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) const & > : function_traits< R( Ts... ) > {};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) && > : function_traits< R( Ts... ) > {};
template< typename R, typename... Ts >
struct function_traits< R( Ts... ) const && > : function_traits< R( Ts... ) > {};
这样,您就可以很容易地限制类中的参数数量:
template <typename Ret, typename T>
class MemberWrapper<Ret T::*>
{
static_assert( function_traits<Ret>::arity <= 4,
"More than 4 arguments are not allowed" );
};
<<p> 生活例子/strong> Boost Function Types提供了大量的函数特征集合。此外,这篇文章也展示了一些例子。
相关文章:
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 特征:模板函数中矩阵的平面图
- 特征模板化函数和维度
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 用于检测函数类型是否为否的特征
- 根据类型特征更改函数定义?
- 以特征类型作为参数的泛型函数回调
- 基于 SFINAE 的特征实现问题与函数模板重载
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 特征::向量;在函数中使用 Eigen::Matrix3f 的值初始化向量,大于 4 个条目
- 带有特征的函数指针
- 特征:创建一个具有函数的三维阵列
- 如何根据传递给函数的变量定义特征矩阵大小
- Lambda 函数在特征中按元素方向
- 特征运算符如何在内部解释为 MKL 函数?
- 为什么不调用预期的函数?我是否对类型特征的理解不正确?
- 使用特征函数失败
- 将函数应用于特征矩阵中的所有元素,而无需循环