【问题标题】:Boost mpl for each and free functionsBoost mpl for each 和 free 函数
【发布时间】:2011-12-02 02:15:05
【问题描述】:

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

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

【问题讨论】:

    标签: c++ templates boost boost-mpl


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
          mpl::for_each<s>(print_type());
      

      这在几个方面是错误的。

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

      其次,print_type 是一个模板函数。您不能在不指定模板参数的情况下调用模板函数。所以print_type() 格式不正确。

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

      【讨论】:

      • 有什么办法至少可以将任何参考价值传递给访问者吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多