1

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

#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;
    }
};

我收到错误 error C2440: 'static_cast' : cannot convert from 'const Generate' to 'wrap &' with [ T=int ]

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

4

1 回答 1

3

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

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

或者

static_cast<wrap<int>const&>(generated) // add const
于 2011-05-01T12:28:02.420 回答