【问题标题】:Why does type knowledge disappear with Boost::MPL?为什么类型知识会随着 Boost::MPL 消失?
【发布时间】:2011-05-01 12:13:30
【问题描述】:

我有以下代码,它工作正常。

#include <boost\mpl\vector.hpp>
#include <boost\mpl\fold.hpp>
#include <boost\mpl\for_each.hpp>
#include <boost\mpl\inherit.hpp>
#include <boost\mpl\inherit_linearly.hpp>
#include <iostream>

using namespace boost::mpl::placeholders;

typedef boost::mpl::vector<short[2], long, char*, int> member_types;

template <typename T>
struct wrap
{
    T value;
};

struct print
{
    template <typename T>
    void operator()(T) const
    {
        std::cout << typeid(T).name() << std::endl;
    }
};

typedef boost::mpl::inherit_linearly<member_types, boost::mpl::inherit<wrap<_2>, _1> >::type Generate;

void main()
{
    Generate generated;
    print p;

    std::cout << static_cast<wrap<int>&>(generated).value << std::endl;

    boost::mpl::for_each<member_types>(p);
}

但如果我这样修改:

struct print
{
    Generate generated;
    template <typename T>
    void operator()(T) const
    {
        std::cout << static_cast<wrap<int>&>(generated).value << std::endl;
    }
};

我得到了错误 错误 C2440:“static_cast”:无法从“const Generate”转换为“wrap &” [ T=整数 ]

为什么它可以在 main 中工作,但如果我将其放入模块中则不能?如何将数据放入可以使用由类型列表创建的数据的值,以由类型列表驱动的一系列模板函数调用。基本上我如何制作一个对这两个部分有用的对象?

【问题讨论】:

标签: c++ templates metaprogramming boost-mpl


【解决方案1】:

如果您将print 中的operator() 更改为以下内容,则可能是 代码可以编译:

struct print {
    ...
    void operator()(T) // remove const

static_cast<wrap<int>const&>(generated) // add const

【讨论】:

  • 太棒了!你可以想象我真的对那个摸不着头脑。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
相关资源
最近更新 更多