2012-07-01 44 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"); 
} 

基本上,我希望類ObjectMaker保存傳遞給構造函數Foo的參數,並在調用ObjectMaker::create()時使用它們。我無法弄清楚的是如何從tuple中獲取值到Foo的構造函數?如何使用std :: tuple中的值作爲函數參數?

+1

你可以看看[這個問題](http://stackoverflow.com/a/4121942/246886)。 –

+1

[「解包」一個元組以調用匹配函數指針]的可能重複(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"); 
} 
相關問題