微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

函数重载函数内部的操作是一样的我必须重写所有内容吗?

如何解决函数重载函数内部的操作是一样的我必须重写所有内容吗?

我有一堆输入 xy函数。我允许输入类型通过引用传递(如果它已经存在)和通过临时输入传递(使用 &&)(如果不存在并且需要创建一个临时对象)。

基本上,我定义和重载函数如下

double foo(const std:::vector<int> & x,const std:::vector<int> &  y){
// Do something
}
double foo(const std:::vector<int> & x,std:::vector<int>&& y){
// Do something
}
double foo(std:::vector<int>&& x,const std:::vector<int> &  y){
// Do something
}
double foo(std:::vector<int>&& x,std:::vector<int>&& y){
// Do something
}

//Do something 完全相同,但唯一的区别是输入类型。有没有一种方法可以在没有太多冗余的情况下简化代码?我不想有 foo(std:::vector<int> x,std:::vector<int> y) 内存问题。

编辑: 有时我还必须稍微修改输入。对于 std::vector<int> &,std::vector<int> &&,const std::vector<int> &x,可能存在三种类型 y 的不同子集。

正如@AVH 所指出的(谢谢!),如果它只是来自 std::vector<int> &&,const std::vector<int> &const std::vector<int> & 应该足以完成这项工作。

结合@Ken Wayne VanderLinde 和@NathanOliver 的两个答案,我能够编写一个函数,将 y 限制为仅 std::vector<int> &&,const std::vector<int> & 并将 x 限制为任何 ``std::vector &,std ::vector &&,const std::vector &` 通过写入

template<class T2,std::enable_if_t<std::is_same_v<std::decay_t<T2>,std::vector<int>>,bool> = true>        
void foo(T2 && a,const std::vector<int> & b){}

解决方法

由于函数都做同样的事情,它们显然不会修改输入。在这种情况下,甚至不要理会右值引用,而只需使用 const 左值引用。即,这是您唯一需要的功能:

double foo(const std:::vector<int> & x,const std:::vector<int> & y){
// Do something
}

临时变量将绑定到 const 左值引用,因此这个函数可以处理临时变量和非临时变量。

,

您可以使用单个函数模板来完成此操作,而不是编写四个重载。这样做会给你一个像

这样的功能
template <typename Vec1,typename Vec2,std::enable_if_t<std::is_same_v<std::decay_t<Vec1>,std::vector<int>> &&
                           std::is_same_v<std::decay_t<Vec2>,std::vector<int>>,bool> = true>
double foo(Vec1&& x,Vec2&& y)
{
    // stuff
}

现在 xy 可以是左值或右值 std::vector<int>,也可以不是 const

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。