如何避免模板函数返回类型重复?

How to avoid duplication on template function return type?

本文关键字:返回类型 函数 何避免      更新时间:2023-10-16

有没有办法避免重复并提高模板函数返回类型的可读性?

这是一个例子

template <typename FunctionType>
std::enable_if_t<
!std::is_void_v<std::invoke_result_t<FunctionType, MyClass*>>,
std::optional<std::invoke_result_t<FunctionType, MyClass*>>
> CallIfValid(MyClass* instance, FunctionType func)
{
using InvocationType = std::invoke_result_t<FunctionType, MyClass*>;
if (instance != nullptr)
{
return func(instance);
}
else
{
return std::optional<InvocationType>();
}
}

请注意std::invoke_result_t<FunctionType, MyClass*>最终如何在返回类型中重复两次,在方法主体中重复第三次。

我在这里没有看到的任何建议或技巧?

谢谢

我有同样的问题。在我个人看来,没有一个好的真正的解决方案,不适用于一般情况。但是,您可以使用一些缓解措施/解决方法。在您的示例中,您可以添加默认模板参数。此外,由于您指定了返回类型,因此无需在返回表达式中重复该类型:

template <typename FunctionType, class InvocationType  = std::invoke_result_t<FunctionType, MyClass*>>
std::enable_if_t<
!std::is_void_v<InvocationType >,
std::optional<InvocationType >
> CallIfValid(MyClass* instance, FunctionType func)
{
if (instance != nullptr)
{
return func(instance);
}
else
{
return std::nullopt; // if you want to be explicit (I personally prefer this)
// return {}; // if you want to be terse
}
}