gpt4 book ai didi

c++ - 如何使用 std::tuple 中的值作为函数参数?

转载 作者:太空狗 更新时间:2023-10-29 23:07:53 25 4
gpt4 key购买 nike

#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 的构造函数?

最佳答案

无耻地应用了 "unpacking" a tuple to call a matching function pointer 中列出的代码和概念由@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");
}

关于c++ - 如何使用 std::tuple 中的值作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11279044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com