成员函数特征

Member function traits

本文关键字:特征 函数 成员      更新时间:2023-10-16

我正在编写一个封装成员函数以减少调用的模板类-如果某些条件为真,则不需要调用成员函数。签名看起来像这样

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提供了大量的函数特征集合。此外,这篇文章也展示了一些例子。