使用Boost获取成员函数的数量和参数类型? (升压::function_traits)

2024-04-26

对于普通的普通函数来说,它工作得很好。下面的代码工作得很好。它只打印应该的内容:

int __cdecl(int, char)
2
int,char

#include <boost/type_traits.hpp>
#include <boost/function.hpp>
#include <boost/typeof/std/utility.hpp>

#include <iostream>

using std::cout;
using std::endl;

int foo(int, char) {
 return 0;
}
int main() {
    typedef BOOST_TYPEOF(foo) foo_type;;
    typedef boost::function_traits<foo_type> function_traits;

    cout << typeid(foo_type).name() << endl;
    cout << function_traits::arity << endl;
    cout << typeid(function_traits::arg1_type).name() << ",";
    cout << typeid(function_traits::arg2_type).name() << endl;

    return 0;
}

那么,问题是,如果 foo 是类 bar 的成员函数,该如何做到这一点呢?

struct bar {
    int foo(int, char) { return 0; }
};

我尝试了这些构造的无数组合: BOOST_TYPEOF_INCRMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TYPE() boost::ref boost::remove_pointer boost::bind boost::mem_fn

等等,等等……没有喜悦。


升压功能类型 http://www.boost.org/doc/libs/1_41_0/libs/function_types/doc/html/index.html可能是自然的解决方案:

#include <boost/function_types/function_type.hpp>
#include <boost/function_types/parameter_types.hpp>
#include <boost/function_types/function_arity.hpp>
#include <boost/typeof/std/utility.hpp>
#include <boost/typeof/typeof.hpp>
#include <iostream>

struct bar {
    int foo(int, char) { return 0; }
};

int main() {

    typedef BOOST_TYPEOF(&bar::foo) foo_type;

    std::cout << typeid(foo_type).name() << std::endl;
    std::cout << boost::function_types::function_arity<foo_type>::value << std::endl;
    std::cout << typeid(boost::mpl::at_c<boost::function_types::parameter_types<foo_type>,1>::type).name() << ",";
    std::cout << typeid(boost::mpl::at_c<boost::function_types::parameter_types<foo_type>,2>::type).name() << ",";

    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Boost获取成员函数的数量和参数类型? (升压::function_traits) 的相关文章