如何根据其ARITY(或编译时已知的其他信息)以不同的方式调用函数对象

How to call a function object differently, depending on its arity (or other information known at compile time)?

本文关键字:信息 其他 对象 函数 调用 方式 ARITY 何根 编译      更新时间:2023-10-16

在功能模板中,我想以函数为单位或函数对象,具体取决于其ARITY(它需要多少参数)。在伪代码:

if arity(f) == 1:
    f(x)
if arity(f) == 2:
    f(x, y)
if arity(f) == 3:
    f(x, y, z)

如何在C ?

中完成此操作

edit 要澄清难度:f(x, y, z)如果f仅采用2个参数,则不会编译,反之亦然,f(x, y)f需要3个参数时不会编译。

带有C 11:

#include <iostream>
template <typename F> struct Traits;
template <typename R, typename... A>
struct Traits<R (A...)>
{
    static constexpr unsigned Arity = sizeof...(A);
};
void f(int, int, int);
int main() {
    std::cout
        << Traits<void()>::Arity
        << Traits<void(int)>::Arity
        << Traits<void(int, int)>::Arity
        << Traits<decltype(f)>::Arity
        << 'n';
    return 0;
}

否则,您可以查找boost ::功能:http://www.boost.org/doc/libs/1_55_0b1/doc/html/function.html