gpt4 book ai didi

c++ - 将一个函数元组应用于一个值并返回一个元组

转载 作者:可可西里 更新时间:2023-11-01 18:37:07 25 4
gpt4 key购买 nike

现在,我有以下方法可以将两个函数应用于一个值并返回一个 2 值元组:

template<typename F1, typename F2>
class Apply2
{
public:
using return_type = std::tuple<typename F1::return_type, typename F2::return_type>;

Apply2(const F1& f1, const F2& f2) : f1_(f1), f2_(f2) {}

template<typename T> return_type operator()(const T& t) const
{
return std::make_tuple(f1_(t), f2_(t));
}

protected:
const F1& f1_;
const F2& f2_;
};

我想将其概括为 N 个函数:

template<typename ...F>
class ApplyN
{
public:
using return_type = std::tuple<typename F::return_type...>;

ApplyN(const std::tuple<F...>& fs) : functions_(fs) {}

template<typename T> return_type operator()(const T& t) const
{
return ???;
}

protected:
std::tuple<F...> functions_;
};

我知道我可能需要以某种方式使用模板递归,但我无法理解它。有什么想法吗?

最佳答案

这花了我一段时间,但在这里(使用 indices ):

template<typename ...F>
class ApplyN
{
public:
using return_type = std::tuple<typename F::return_type...>;

ApplyN(const F&... fs) : functions_{fs...} {}

template<typename T> return_type operator()(const T& t) const
{
return with_indices(t, IndicesFor<std::tuple<F...> >{});
}

protected:
std::tuple<F...> functions_;

template <typename T, std::size_t... Indices>
return_type with_indices(const T& t, indices<Indices...>) const
{
return return_type{std::get<Indices>(functions_)(t)...};
}
};

之前有人有一个(不完整的)答案,但他/她删除了它——那是我的出发点。不管怎样,谢谢陌生人!也谢谢你 R. Martinho Fernandes!

关于c++ - 将一个函数元组应用于一个值并返回一个元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589867/

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