如何删除相似的经过ref限定的成员函数之间的代码重复? [英] How do I remove code duplication between similar ref-qualified member functions?
问题描述
类似于如何删除相似的const和非const成员函数之间的代码重复?,我要删除
假设我有一个类似这样的类:
Let's say I have a class that's something like this:
class MyStringBuilder
{
std::string member;
public:
// Other functions
std::string create() const& {
// Some work
std::string result = member;
// More work
return result;
}
std::string create() && {
// Some work
std::string result = std::move(member);
// More work
return result;
}
};
对于构建器对象我们想这样做并非不可想象,因为如果我们使用 MyStringBuilder
完成。
It's not inconceivable that we would want to do this for a builder object, as it saves a copy if we are done with the MyStringBuilder
.
除了使用成员的地方,<$ c $之间的代码c> const& 版本与&
版本相同。这两个函数之间的唯一区别是&&
版本 std :: move
时,任何成员
Except for where members are used, the code between the const&
version and &&
version are identical. The only difference between the two functions is that the &&
version std::move
s any members whenever they are referenced.
如何避免此代码重复?
推荐答案
您可以做的一件事是,您可以在非成员函数中实现逻辑,并将 * this
的类型作为模板参数:
One thing you can do is you can implement the logic in a non-member function and take the type of *this
as a template parameter:
class MyStringBuilder
{
std::string member;
template<typename Self>
static std::string create_impl(Self&& self) {
// Some work
std::string result = std::forward<Self>(self).member;
// More work
return result;
}
public:
// Other functions
std::string create() const& {
return create_impl(*this);
}
std::string create() && {
return create_impl(std::move(*this));
}
};
这篇关于如何删除相似的经过ref限定的成员函数之间的代码重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!