从模板参数获取函数参数
Get function arity from template parameter
如何获取用作模板参数的任意函数类型的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;
}
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 有没有办法在从编译器获取参数时避免预处理器宏?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 如何从参数中获取函数签名?
- 获取可变参数模板参数包的相关类型
- 在 C++11 中获取函子作为参数
- 如何使用可变参数模板获取参数的变量号及其大小C++
- 是否可以获取成员函数模板参数的拥有对象?
- 如何从 x64 程序集中的堆栈中获取参数?
- 获取第一个模板参数的可靠方法
- 如何从参数包获取指向对象的指针
- C++ 如何使派生类自动获取基类参数
- 通过命令行参数获取llvm ir文件时面临问题
- 在C++中,是否允许将函数指针强制转换为将指向基类或派生类的指针作为参数获取的函数指针
- 使用一个可选参数获取两个参数到main
- cpp 映射作为函数参数获取警告信息 "discards qualifiers"
- 从控制台应用中的命令行参数获取文件名C++
- 从模板参数获取函数参数
- 使用参数获取其他参数