c – 每个和自由函数的Boost mpl
发布时间:2020-12-16 09:38:51 所属栏目:百科 来源:网络整理
导读:为什么这段代码不能编译: #include boost/mpl/vector.hpp#include boost/mpl/for_each.hpp#include iostreamusing namespace std;using namespace boost;template class T // specific visitor for type printingstatic void print_type(T t) { std::cout t
为什么这段代码不能编译:
#include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include <iostream> using namespace std; using namespace boost; template <class T> // specific visitor for type printing static void print_type(T t) { std::cout << typeid(T).name() << std::endl; } typedef mpl::vector<int,long,char*> s; int main () { mpl::for_each<s>(print_type()); } 我想知道 – 如何使用同一类中的自由函数使boost mpl for_each工作? 解决方法
如上所述,你需要一个仿函数.
下面的代码包含一个额外的包装模板,允许打印仿函数处理引用. #include <iostream> #include <typeinfo> #include <boost/mpl/vector.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/placeholders.hpp> using namespace std; using namespace boost; template <typename T> struct wrap {}; struct print_type { template< typename T> void operator()( wrap<T> ) const { cout << typeid(T).name() << "n"; } }; typedef mpl::vector<int,long&,char*> s; int main () { mpl::for_each<s,wrap<mpl::placeholders::_1> >(print_type()); return 0; } 注意:此代码基于David Abrahams和Aleksy Gurtovoy撰写的“C模板元编程”一书中的示例 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |