为什么这段代码不能编译:
#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工作与同一类的自由函数?
如上所述,您需要一个函子。
下面的代码包含一个额外的换行模板,该模板允许print函函数处理引用。
#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++ Template Metaprogramming》中的示例
mpl::for_each<s>(print_type());
这在几个方面都是错误的。
首先,print_type
是一个返回void
的函数。print_type()
尝试调用该函数。因为它不返回任何东西,所以你不能把它不存在的返回值插入到其他东西中。
第二,print_type
是模板函数。如果不指定模板参数,就不能调用模板函数。所以print_type()
是病态的
第三,即使mpl::for_each<s>(print_type)
也不起作用,因为print_type
不是一个值(也不能转换为一个值);它是一个模板。不能将模板作为函数的参数传递。这就是为什么访问者(对于很多东西,不仅仅是MPL)是对象,它可以有模板operator()
成员。