2012-08-14 51 views
1

我學習的boost :: MPL和我有下面的類 -如何實例化一個沒有默認構造函數的類型的boost :: fusion :: vector成員變量?

#include <string> 

#include <boost/mpl/vector.hpp> 
#include <boost/mpl/size.hpp> 
#include <boost/mpl/at.hpp> 

#include <boost/fusion/include/mpl.hpp> 
#include <boost/fusion/container.hpp> 


using namespace boost; 
using namespace std; 

template< typename T > 
class Demo 
{ 
public: 
    typedef boost::mpl::size<T> NumDimensions; 

    template< size_t D > 
    struct Dim 
    { 
     typedef typename boost::mpl::at_c< T, D >::type Type; 
    }; 

    template< size_t D > 
    typename Dim<D>::Type& GetElement() 
    { 
     return fusion::at_c<D>(elements_); 
    } 

private: 
    typename fusion::result_of::as_vector<T>::type elements_; 
}; 

這工作得很好,只要我使用類型的默認構造函數(或默認類型)

int main(int argc, char *argv[]) 
{ 
    typedef Demo< boost::mpl::vector< int, std::string > > D1; 
    D1 d; 
    D1::Dim<0>::Type &i = d.GetElement<0>(); 

    i = "Hello World!"; 

    cout << " " << i << endl; 
} 

然而,如果我使用沒有默認構造函數的類型,它會引發編譯器錯誤,因爲矢量初始化失敗。有沒有一種標準的方式來正確地初始化成員(在構造函數中)而不訴諸指針/引用?

回答

1

您可以使用fusion::vector的構造:

#include <string> 

#include <boost/mpl/vector.hpp> 
#include <boost/mpl/size.hpp> 
#include <boost/mpl/at.hpp> 

#include <boost/fusion/include/mpl.hpp> 
#include <boost/fusion/container/vector.hpp> 
#include <utility> 

struct foo { 
    explicit foo(int){} 
}; 

template< typename T > 
class Demo 
{ 
public: 
    //You don't need to use variadic templates and perfect forwarding 
    //but you may need to emulate them to get this effect (depending on 
    //where exactly you need to construct Demo). 
    //Another alternative would be to pass in a fusion::vector, and 
    //copy construct `elements` with that vector. 
    template<typename ...Args> 
    Demo(Args&& ...args) : elements_(std::forward<Args>(args)...) {} 

    typedef boost::mpl::size<T> NumDimensions; 

    template< size_t D > 
    struct Dim 
    { 
     typedef typename boost::mpl::at_c< T, D >::type Type; 
    }; 

    template< size_t D > 
    typename Dim<D>::Type& GetElement() 
    { 
     return boost::fusion::at_c<D>(elements_); 
    } 

private: 
    typename boost::fusion::result_of::as_vector<T>::type elements_; 
}; 

int main() { 
    Demo<boost::mpl::vector< foo, std::string > > a(foo(10),"hi"); 
} 
相關問題