【发布时间】: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