2012-07-01 3 views
3
#include <tuple> 

class Foo { 
public: 
    Foo(int i, double d, const char* str) { } 
}; 

template<class T, class... CtorArgTypes> 
class ObjectMaker { 
public: 
    ObjectMaker(CtorArgTypes... ctorArgs) : m_ctorArgs(ctorArgs...) 
    { 
    } 
    Foo* create() 
    { 
     //What do I do here? 
    } 
private: 
    std::tuple<CtorArgTypes...> m_ctorArgs; 
}; 

int main(int, char**) 
{ 
    ObjectMaker<Foo, int, double, const char*> fooMaker(42, 5.3, "Hello"); 
    Foo* myFoo = fooMaker.create();  //this should do new Foo(42, 5.3, "Hello"); 
} 

는 기본적으로, Foo의 생성자에 전달 될 인수를 저장하고 ObjectMaker::create()를 호출 할 때 그들을 사용하는 클래스 ObjectMaker를 원한다. 내가 알 수없는 것은 tuple의 값을 Foo의 생성자로 가져 오는 방법입니다.std :: tuple의 값을 함수 인수로 사용하려면 어떻게해야합니까?

+1

[이 질문을 볼 수 있습니다 (http://stackoverflow.com/a/4121942/246886). –

+1

일치하는 함수 포인터를 호출하는 튜플 [ "unpacking"가능한 중복] (http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer) – Xeo

+2

Btw 코드 마크 업을 위해 HTML 태그를 사용하지 말고, 인라인에는 백틱을, 코드 블록에는 네 개의 선행 공백 (또는 마크 및 Ctrl-K)을 사용하십시오. – Xeo

답변

1

& 코드가 @Xeo에 의해 연결된 "unpacking" a tuple to call a matching function pointer에 뻔뻔스럽게 적용되었습니다. 기본 개념은 튜플에 일련의 인덱스를 만들고 std :: get에 대한 호출로 압축을 풀는 것입니다. 아래의 코드는 g ++ 4.5.2에서 작동합니다. 일반적으로 msvc10을 사용하므로 재미는 아직 없습니다. 멋진 것들!

#include <tuple> 
#include <iostream> 

class Foo { 
public: 
    Foo(int i, double d, const char* str) 
    { 
     std::cout << "Foo constructor: i=" << i << " d=" << d << "str=" << str << std::endl; 
    } 
}; 


template<int ...> 
struct seq { }; 

template<int N, int ...S> 
struct gens : gens<N-1, N-1, S...> { }; 

template<int ...S> 
struct gens<0, S...> { 
    typedef seq<S...> type; 
}; 



template<class T, class... CtorArgTypes> 
class ObjectMaker { 
public: 
    ObjectMaker(CtorArgTypes... ctorArgs) : m_ctorArgs(ctorArgs...) 
    { 
    } 

    Foo* create() 
    { 
     return create_T(typename gens<sizeof ...(CtorArgTypes)>::type()); 
    } 

private: 
    template< int ...S > 
    T* create_T(seq<S...>) 
    { 
     return new T(std::get<S>(m_ctorArgs) ...); 
    } 

    std::tuple<CtorArgTypes...> m_ctorArgs; 
}; 



int main(int, char**) 
{ 
    ObjectMaker<Foo, int, double, const char*> fooMaker(42, 5.3, "Hello"); 
    Foo* myFoo = fooMaker.create();  //this should do new Foo(42, 5.3, "Hello"); 
} 
관련 문제