3

为什么这段代码不能编译:

#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 与同一类的免费函数一起工作?

4

2 回答 2

4

如前所述,您需要一个仿函数。

下面的代码包括一个额外的包装模板,它允许打印函子处理引用。

#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++ 模板元编程”一书中的示例

于 2011-12-13T09:24:20.307 回答
3
    mpl::for_each<s>(print_type());

这在几个方面是错误的。

首先,print_type是一个返回的函数voidprint_type()是尝试调用该函数。由于它不返回任何内容,因此您不能将其不存在的返回值粘贴到其他内容中。

print_type模板功能。不指定模板参数就不能调用模板函数。print_type()病态也是如此。

第三, evenmpl::for_each<s>(print_type)不起作用,因为print_typeis 不是一个值(也不能转换为一个值);它是一个模板。您不能将模板作为函数的参数传递。这就是为什么访问者(对于许多事情,不仅仅是 MPL)是可以具有模板operator()成员的对象。

于 2011-12-02T02:19:45.117 回答