Pra*_*han 5 c++ templates variadic-templates c++11
我正在编写一个模板类,它包含成员函数以减少一些调用 - 如果某些条件为真,则不需要调用成员函数.签名看起来像这样
template <typename MemFuncType, MemFuncType> class MemberWrapper;
Run Code Online (Sandbox Code Playgroud)
我可以专门研究它:
template <typename R, typename T, R T::* MemFunc> class MemberWrapper<R T::*, MemFunc>{};
Run Code Online (Sandbox Code Playgroud)
我还想限制参数的数量R T::*.我该怎么做呢?
我能想到的唯一解决方案是通过提供基于返回类型,函数类型,参数列表和cv限定符的部分特化来实现成员函数特征类.这将导致像当前std::mem_fn 重载一样繁琐的实现.有没有办法做得更好?
编辑:更改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... ) > {};
Run Code Online (Sandbox Code Playgroud)
有了它,您可以轻松地限制类中的参数数量:
template <typename Ret, typename T>
class MemberWrapper<Ret T::*>
{
static_assert( function_traits<Ret>::arity <= 4,
"More than 4 arguments are not allowed" );
};
Run Code Online (Sandbox Code Playgroud)