2011-05-01 63 views
1

我有以下代碼,它工作正常。爲什麼類型知識會隨着Boost :: MPL消失?

#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:不能從 '常量生成' 轉換爲 '包裹&' 與 [ T = int ]

爲什麼它在main中工作,但不是如果我把它放到一個模塊中?如何將數據獲取到一個地方我可以使用類型列表創建的數據的值由類型列表驅動的一系列模板函數調用。基本上我該如何製作一個對這兩部分有用的對象?

+0

http://stackoverflow.com/questions/5790161/is反斜線可接受的c和c包括指令 – fazo 2011-05-01 12:36:15

回答

3

如果您在print改變operator()以下內容,可能是 代碼可以編譯:

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

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

絕對太棒了!你可以想象我真的很抓狂。再次感謝。 – Tavison 2011-05-01 12:31:27

+0

不客氣:-) – 2011-05-01 13:24:11