从模板参数获取函数arity

Vit*_*meo 11 c++ function arity c++11 c++14

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

该函数可以是普通函数,lambda或函子.例:

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
}
Run Code Online (Sandbox Code Playgroud)

我可以访问所有C++ 14功能.

我是否必须为每种函数类型(以及所有相应的限定符)创建特化?或者有更简单的方法吗?

Col*_*mbo 11

假设operator()我们所讨论的所有和函数都不是模板或重载:

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
Run Code Online (Sandbox Code Playgroud)

演示.

  • 是否有像您这样的版本也支持通用Lambda?http://coliru.stacked-crooked.com/a/1192b2686726d41d (2认同)