gpt4 book ai didi

c++ - 返回类型的模板推导

转载 作者:行者123 更新时间:2023-12-05 02:26:57 26 4
gpt4 key购买 nike

我有一个函数会重试某个函数一定次数并返回它是否成功:

template<typename Functor>
bool Attempt(Functor functor)
{
bool success = false;
size_t retries = MAX_RETRIES;
do
{
success = functor();
}
while (!success && retries-- > 0);
return success;
}

// usage:
bool success = Attempt([=]() {
return something_that_may_not_work_the_first_time();
});

这很好用,并且在我需要多次重试的代码中使用(例如串行通信)。

但是我最近需要Attempt返回 std::optional<> 的东西.

我想出的是这个:

template <typename T, typename Functor>
std::optional<T> Attempt(Functor functor)
{
std::optional<T> success{};
size_t Retries = MAX_VALIDATION_RETRIES;
do
{
success = functor();
}
while (!success && Retries-- > 0);
return success;
}

// usage
std::optional<unsigned int> response = Attempt<unsigned int>([=]() {
return something_that_returns_optional_unsigned_int();
});

哪个有效但难看 <unsigned int>在赋值运算符的两边。

是否可以添加任何模板诡计来推断出这一点?

最佳答案

您明确指定的所有类型都可以推导:

#include <optional>

template <typename Functor>
auto Attempt(Functor functor)
{
decltype(functor()) success{};
size_t Retries = 42;
do
{
success = functor();
}
while (!success && Retries-- > 0);
return success;
}

std::optional<unsigned int> something_that_returns_optional_unsigned_int() { return {};};

int main() {
auto response = Attempt([]{ return something_that_returns_optional_unsigned_int(); });
}

关于c++ - 返回类型的模板推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73473548/

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