从模板参数获取函数arity [英] Get function arity from template parameter

查看:337
本文介绍了从模板参数获取函数arity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得用作模板参数的任意函数类型的实例?



函数可以是普通函数,lambda或函子。示例:

 模板< typename TFunc> 
std :: size_t getArity()
{
// ...?
}

template< typename TFunc>
void printArity(TFunc mFunc)
{
std :: cout< arity:< getArity< TFunc>()<< std :: endl;
}

void testFunc(int){}

int main()
{
printArity ; // prints 0
printArity([&](int x,float y){}); // prints 2
printArity(testFunc); // prints 1
}



我可以访问所有C ++ 14功能。 / p>

我必须为每个函数类型(和所有各自的限定符)创建专门化吗?
或者有更简单的方法吗?

解决方案

假设所有 / code>和我们讨论的函数不是模板或重载的:

  template< typename T> ; 
struct get_arity:get_arity< decltype(& T :: operator())> {};
template< typename R,typename ... Args>
struct get_arity< R(*)(Args ...)> :std :: integral_constant< unsigned,sizeof ...(Args)> {};
//可能为可变函数添加专门化
//成员函数:
template< typename R,typename C,typename ... Args>
struct get_arity< R(C :: *)(Args ...)> :
std :: integral_constant< unsigned,sizeof ...(Args)> {};
template< typename R,typename C,typename ... Args>
struct get_arity< R(C :: *)(Args ...)const> :
std :: integral_constant< unsigned,sizeof ...(Args)> {};

//添加可变参数/非可变参数,cv-qualifiers和ref-qualifiers的所有组合

演示


How can I get the arity of an arbitrary function type used as a template parameter?

The function can be a normal function, a lambda or a functor. Example:

template<typename TFunc>
std::size_t getArity() 
{
    // ...? 
}

template<typename TFunc>
void printArity(TFunc mFunc)
{
    std::cout << "arity: " << getArity<TFunc>() << std::endl;
}

void testFunc(int) { }

int main()
{
    printArity([](){}); // prints 0
    printArity([&](int x, float y){}); // prints 2
    printArity(testFunc); // prints 1
}

I have access to all C++14 features.

Do I have to create specialization for every function type (and all respective qualifiers)? Or is there an easier way?

解决方案

Assuming that all the operator()'s and functions we're talking about are not templates or overloaded:

template <typename T>
struct get_arity : get_arity<decltype(&T::operator())> {};
template <typename R, typename... Args>
struct get_arity<R(*)(Args...)> : std::integral_constant<unsigned, sizeof...(Args)> {};
// Possibly add specialization for variadic functions
// Member functions:
template <typename R, typename C, typename... Args>
struct get_arity<R(C::*)(Args...)> :
    std::integral_constant<unsigned, sizeof...(Args)> {};
template <typename R, typename C, typename... Args>
struct get_arity<R(C::*)(Args...) const> :
    std::integral_constant<unsigned, sizeof...(Args)> {};

// Add all combinations of variadic/non-variadic, cv-qualifiers and ref-qualifiers

Demo.

这篇关于从模板参数获取函数arity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆