2012-08-14 5 views
1

것은 내가 부스트 : : 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"); 
}