如何避免模板函数返回类型重复?
How to avoid duplication on template function return type?
有没有办法避免重复并提高模板函数返回类型的可读性?
这是一个例子
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
}
}
相关文章:
- 如何获取std::result_of函数的返回类型
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 模板返回类型函数如何在C++中工作
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 在引用或指针返回类型函数上输入
- 在后面的返回类型函数语法中,auto关键字背后是否有意图
- 我可以在c++中重写字符串返回类型函数吗?