为什么类型知识在Boost::MPL中消失了?

Why does type knowledge disappear with Boost::MPL?

本文关键字:MPL 消失了 Boost 类型 知识 为什么      更新时间:2023-10-16

我有下面的代码,它工作得很好。

#include <boostmplvector.hpp>
#include <boostmplfold.hpp>
#include <boostmplfor_each.hpp>
#include <boostmplinherit.hpp>
#include <boostmplinherit_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 = int)

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

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

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

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