【问题标题】:Getting boost::function arity at compile time?在编译时获得 boost::function arity?
【发布时间】:2010-09-15 04:17:52
【问题描述】:

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

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

【问题讨论】:

  • 预处理器没有类型或值的概念,除了整数文字。它不知道函数是什么。
  • 只有模板为您提供编译时分支,而不是在编译前作为单独阶段运行的预处理器。

标签: c++ function boost boost-preprocessor


【解决方案1】:
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&lt;F&gt;::value 生成 if/else 条件

【讨论】:

    【解决方案2】:

    由于某种原因,我的包含不断中断但不在预览中 =[

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 根据要求,这并不能在编译时获得函数的数量。
      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多