使用Boost获取成员函数的数量和参数类型? (升压::function_traits)
对于普通的普通函数来说,它工作得很好。下面的代码工作得很好。它只打印应该的内容:
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
等等,等等...没有乐趣。
It works just fine, for plain vanilla functions. The code below works just fine. It prints just what is should:
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;
}
So, the question is, how can one do this if foo is a member function of class bar?
struct bar {
int foo(int, char) { return 0; }
};
I have tried countless combinations of these constructs: BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() BOOST_TYPEOF_REGISTER_TYPE() boost::ref boost::remove_pointer boost::bind boost::mem_fn
etc., etc... No joy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Boost 函数类型 可能是自然的解决方案:
Boost Function Types would probably be the natural solution:
这可以通过更新的 boost lib 来完成(可调用特征,额外的好处:它也可以与 lambda 一起使用)。
我还添加了另一个带有人类可读输出的打印输出,尽管不确定问题是否需要它。
海湾合作委员会输出:
This can be done with newer boost lib(callable traits, bonus: it works with lambdas also).
I have also added the another printout with a human readable output, although not sure if the question demands it.
gcc output:
科内尔·基西莱维奇(Kornel Kisielewicz)做到了。这是与测试消息分开的解决方案。
Kornel Kisielewicz nailed it. Here it is with the solution separated from the test-messages.