如何编写 Const 和 Mutable 重载代码?
我的代码中似乎经常出现这种模式,除了参数/返回的常量性之外,两个函数执行相同的任务。
int& myClass::getData()
{
return data;
}
// called for const objects
const int& myData::getData() const
{
return data;
}
这冒犯了我的 DRY 观念。对于单行代码来说这不是问题,但是随着 getData() 变大,就会出现明显的重复。
我知道为什么我需要这两种方法,但觉得应该有更好的方法来实现它。是否有一个模板技巧可以提供帮助,或者我应该有一种方法来调用另一种方法来根据需要来回转换常量?
添加:作为一个更真实的示例,下面是典型 STL vector::at() 实现的示例:
const_reference at(size_type _Off) const
{ // subscript nonmutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}
reference at(size_type _Off)
{ // subscript mutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}
I seem to have this pattern occuring pretty often in my code, with two functions performing the same task apart from the constness of their parameters/returns.
int& myClass::getData()
{
return data;
}
// called for const objects
const int& myData::getData() const
{
return data;
}
This offends my sense of DRY. It's not a problem for a one-liner, but as getData() gets bigger, there's obvious duplication.
I know WHY I need both methods, but feel there should be a better way to implement it. Is there a template trick that can help, or should I have one method which calls the other casting the constness back and forth as required?
ADDED: As a more real-world example, here's a sample of typical STL vector::at() implementation:
const_reference at(size_type _Off) const
{ // subscript nonmutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}
reference at(size_type _Off)
{ // subscript mutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用以下技巧(我最初从 Scott Meyers 的书 Effective C++ 中得到):
显然,对于像这样的短函数,您可能会发现复制代码更容易,但是当您具有更长的函数(例如
vector::at
或者它可能会发生很多变化。Use the following trick (which I originally got from Scott Meyers' book Effective C++):
Obviously for a short function like this, you may find it easier just to duplicate code, but this idiom is useful when you have a longer function (like
vector<T>::at
or it is subject to lots of changes.提供如下功能
可能是错误的 - 您不妨公开“数据”。第二个应该写成:
Providing a function like:
is probably wrong - you might as well make 'data' public. And the second should be written as:
您引用的标准库函数重复代码的原因是标准库函数需要尽可能高性能。在那里调用另一个函数(正如其他人正确建议的那样)可能会搞砸。但您的代码可能受到不太严格的性能限制,因此您应该尽可能使用通用代码。
The reason the Standard Library functions you quote duplicate the code is that Standard Library functions need to be as performant as possible. Putting a call to another function in there (as others have correctly suggested doing) might screw that. But your code is probably under much less stringent performance constraints, so you should use common code, where possible.