c++ - 从模板参数中获取函数参数

标签 c++ function 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
}

我可以访问所有 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

Demo .

关于c++ - 从模板参数中获取函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27866909/

相关文章:

function - AppleScript语法错误

c++ - 带有 C++11 线程库的 boehm-gc

c++ - const-reference 绑定(bind)到一个临时的

c++ - 如何获取点 vector 并仅获取这些点中的 'y'

c++ - 如何获取子进程的入口点?

c++ - 是否可以在 constexpr 函数中遍历枚举成员,因此值是 constexpr?

c++ - 如何将指针从 unique_ptr 传递到另一个对象并管理生命周期?

c++ - 错误 : invalid conversion from 'int (*)[6]' to 'int' [-fpermissive]|

function - 函数可以作为参数传递吗?

c++ - 在 C++ 中设置文件修改时间的可移植方法?