开发者

Getting boost::function arity at compile time?

开发者 https://www.devze.com 2023-01-16 08:51 出处:网络
I need to make a decisi开发者_StackOverflow中文版on in a BOOST_PP_IF statement based on the arity (parameter count) of a boost::function object. Is this possible?

I need to make a decisi开发者_StackOverflow中文版on 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.


function_arity

template<typename F>
struct function_arity;

Header

#include <boost/function_types/function_arity.hpp>

F

    Callable builtin type 
function_arity<F>

    Function arity as MPL - Integral Constant 
function_arity<F>::value

    Constant value of the function arity 

note, this is compile time constant

you should start here: http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/index.html

or use BOOST_PP_SEQ_FOR_EACH/BOOST_PP_REPEAT_FROM_TO to generate if/else conditions against function_arity<F>::value


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


If all you need is to read the arity of a boost::function then you don't need to do that much work:

#include <boost/function.hpp>
#include <iostream>
int main() {
  std::cout << boost::function<void()>::arity << std::endl;
  std::cout << boost::function<void(int)>::arity << std::endl;
  std::cout << boost::function<void(int, int)>::arity << std::endl;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消