从模板参数获取函数参数

Get function arity from template parameter

本文关键字:参数 获取 函数      更新时间:2023-10-16

如何获取用作模板参数的任意函数类型的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
}

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

我是否必须为每个函数类型(以及所有相应的限定符)创建专用化?还是有更简单的方法?

假设我们正在讨论的所有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

演示

多年后,但在这里查看我的完整(免费)解决方案(生产级,完整文档)。在您的情况下,您需要帮助程序模板"ArgCount_v"(完整记录在上面的链接中)。将其应用于您自己的代码(显示您期望的结果 - 请参阅此处):

#include <iostream>
// See https://github.com/HexadigmSystems/FunctionTraits
#include "TypeTraits.h" 
template<typename TFunc>
void printArity(TFunc mFunc)
{
    ////////////////////////////////////////////////
    // Everything in "TypeTraits.h" above declared
    // in this namespace
    ////////////////////////////////////////////////
    using namespace StdExt;
    /////////////////////////////////////////////////////  
    // Note: "tcout" (declared in "TypeTraits.h" above)
    // always resolves to "std::cout" on non-Microsoft
    // platforms and usually "std::wcout" on Microsoft
    // platforms (when compiling for UTF-16 in that
    // environment which is usually the case). You can
    // directly call "std::cout" or "std::wcout" instead
    // if you prefer, assuming you know which platform
    // you're always running on.
    /////////////////////////////////////////////////////  
    tcout << "arity: " << ArgCount_v<TFunc> << std::endl;
}
void testFunc(int) { }
int main()
{
    printArity([](){}); // prints 0
    printArity([&](int x, float y){}); // prints 2
    printArity(testFunc); // prints 1
    return 0;
}