#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
的构造函数中获取?
答案 0 :(得分:1)
无耻地应用代码&amp;由@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");
}