gpt4 book ai didi

c++ - 根据表达式的有效性选择要应用的函数

转载 作者:IT老高 更新时间:2023-10-28 22:08:42 25 4
gpt4 key购买 nike

问题如下,在 C++14 :

  • 让我们有两个函数 FV&& valid_f , FI&& invalid_f , 和参数 Args&&... args
  • 函数apply_on_validity应该申请valid_fargs如果表达式 std::forward<FV>(valid_f)(std::forward<Args>(args)...)有效
  • 否则,如果 std::forward<FV>(invalid_f)(std::forward<Args>(args)...)是一个有效的表达式,apply_on_validity应该申请invalid_fargs
  • 否则apply_on_validity什么都不做

我猜代码应该是这样的:

template <class FV, class FI, class... Args, /* Some template metaprog here */>
void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
{
// Apply valid_f by default
std::forward<FV>(valid_f)(std::forward<Args>(args)...);
}

template <class FV, class FI, class... Args, /* Some template metaprog here */>
void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
{
// Apply invalid_f if valid_f does not work
std::forward<FV>(invalid_f)(std::forward<Args>(args)...);
}

template <class FV, class FI, class... Args, /* Some template metaprog here */>
void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
{
// Do nothing when neither valid_f nor invalid_f work
}

但我真的不知道该怎么做。有什么想法吗?


链接到概括here .

最佳答案

拍摄:

template <int N> struct rank : rank<N-1> {};
template <> struct rank<0> {};

然后:

template <class FV, class FI, class... Args>
auto apply_on_validity_impl(rank<2>, FV&& valid_f, FI&& invalid_f, Args&&... args)
-> decltype(std::forward<FV>(valid_f)(std::forward<Args>(args)...), void())
{
std::forward<FV>(valid_f)(std::forward<Args>(args)...);
}

template <class FV, class FI, class... Args>
auto apply_on_validity_impl(rank<1>, FV&& valid_f, FI&& invalid_f, Args&&... args)
-> decltype(std::forward<FI>(invalid_f)(std::forward<Args>(args)...), void())
{
std::forward<FI>(invalid_f)(std::forward<Args>(args)...);
}

template <class FV, class FI, class... Args>
void apply_on_validity_impl(rank<0>, FV&& valid_f, FI&& invalid_f, Args&&... args)
{

}

template <class FV, class FI, class... Args>
void apply_on_validity(FV&& valid_f, FI&& invalid_f, Args&&... args)
{
return apply_on_validity_impl(rank<2>{}, std::forward<FV>(valid_f), std::forward<FI>(invalid_f), std::forward<Args>(args)...);
}

DEMO

关于c++ - 根据表达式的有效性选择要应用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42030063/

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