Search code examples
c++functionboostboost-preprocessor

Getting boost::function arity at compile time?


I need to make a decision in a BOOST_PP_IF statement based on the arity (parameter count) of a boost::function object. Is this possible?

boost::function_types::function_arity does what I'm looking for, but at runtime; I need it at compile time.


Solution

  • For some reason my includes keep breaking but not in preview =[

    #include <ostream>  
    #include <iostream>  
    #include <boost/function.hpp>  
    
    // Assume that you want to print out "Function is N-arity" for general case. But "nularity" for 0
    
    template< int i >
    struct DarkSide
    {
    template<class U>
    void operator()(std::ostream& out, const U& u) { out << "Function is "<<i<<"-arity"<<u; }
    void operator()(std::ostream& out, std::ostream& ( *pf )(std::ostream&) ) { out << "Function is "<<i<<"-arity"<<pf; }
    };
    
    template<>
    struct DarkSide<0>
    {
    template<class U>
    void operator()(std::ostream& out, const U& u) { out << "Function is nularity"<<u; }
    void operator()(std::ostream& out, std::ostream& ( *pf )(std::ostream&) ) { out << "Function is nularity"<<pf; }
    };
    
    int main() {
    typedef boost::function< void ( ) > vFv;
    typedef boost::function< void ( int x ) > vFi;
    DarkSide< vFv::arity >()(std::cout,"\n");
    DarkSide< vFi::arity >()(std::cout,std::endl);
    }