Search code examples
c++template-meta-programmingarity

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


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.


Solution

  • 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