在编译时获取boost :: function arity?

时间:2010-09-15 04:17:53

标签: c++ function boost boost-preprocessor

我需要根据BOOST_PP_IF对象的arity(参数计数)在boost::function语句中做出决定。这可能吗?

boost::function_types::function_arity正在寻找我正在寻找的东西,但是在运行时;我在编译时需要它。

3 个答案:

答案 0 :(得分:2)

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 

请注意,这是编译时常量

你应该从这里开始: http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/index.html

或使用BOOST_PP_SEQ_FOR_EACH / BOOST_PP_REPEAT_FROM_TO生成针对function_arity<F>::value的if / else条件

答案 1 :(得分:1)

由于某种原因,我的包括保持打破但不在预览= [

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

答案 2 :(得分:-1)

如果您只需阅读boost :: function的arity,那么您不需要做那么多工作:

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