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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 00:23:24

问题


In a function template, I'd like to call a function, or function object differently, depending on its arity (how many arguments it takes). In pseudocode:

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

How can this be done in C++?

Edit To clarify the difficulty: f(x, y, z) won't compile if f only takes 2 arguments, and vice versa, f(x, y) won't compile when f needs 3 arguments.


回答1:


With 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;
}

Otherwise you might lookup boost::function: http://www.boost.org/doc/libs/1_55_0b1/doc/html/function.html



来源:https://stackoverflow.com/questions/21349158/how-to-call-a-function-object-differently-depending-on-its-arity-or-other-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!