如何使用 std::tuple 中的值作为函数参数

How do I use values from an std::tuple as function arguments?

本文关键字:函数 参数 何使用 std tuple      更新时间:2023-10-16
#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的构造函数?

无耻地应用"解包"元组中列出的代码和概念来调用由@Xeo链接的匹配函数指针。 据我了解,基本思想是在元组中创建一个索引序列,并将它们解压缩到对 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");
}