【发布时间】:2018-08-29 15:15:23
【问题描述】:
好的,我做了一些研究,显然有很多关于这个主题的重复问题,仅举几例:
- Elegant solution to duplicate, const and non-const, getters?
- How to avoid operator's or method's code duplication for const and non-const objects?
- How do I remove code duplication between similar const and non-const member functions?
等等。但我忍不住再次提出这个问题,因为
- 使用 c++14
auto类型的返回值,我实际上是在复制函数体,唯一的区别是const函数限定符。 -
const版本和非const版本可能会返回彼此完全不兼容的类型。在这种情况下,Scott Meyers 的const_cast习语和“返回非const的私有const函数”技术都不起作用。
举个例子:
struct A {
std::vector<int> examples;
auto get() { return examples.begin(); }
auto get() const { return examples.begin(); }
}; // Do I really have to duplicate?
// My real-world code is much longer
// and there are a lot of such get()'s
在这种特殊情况下,auto get() 返回一个iterator 而auto get() const 返回一个const_iterator,并且两者不能相互转换(我知道erase(it,it) 技巧在这种情况下会进行转换,但那是不是重点)。 const_cast 因此不起作用;即使成功了,也需要程序员手动推导出auto的类型,完全违背了使用auto的目的。
那么除了宏真的没有别的办法了吗?
【问题讨论】:
-
How do I remove code duplication between similar const and non-const member functions? 的可能重复项我不明白在其他问题中如何回答。
-
@Drise 在这种情况下,该技术似乎并不适用,因为
::const_iterator != const ::iterator -
Meyer 的方法显然不适用于在
const和非const版本中返回不同类型的成员函数,但我想说这是一个相当罕见的情况,在迭代器之外(虽然我可能是错的)。不确定是否有可能制定出一个通用的解决方案,但也许你可以拥有convertconst_iteratortoiterator的函数(比如unconst_iterator)并拥有像auto get() { return unconst_iterator(example, static_cast<const A &>(*this).get()); }这样的模式。 -
@jdehesa 很公平。在我的情况下,它不是
iterator,而是非常接近的东西(两个类似的类,一个有const成员)。我确实可以在两者之间编写类型转换。感谢您的建议,但仍希望等待更优雅的答案。 -
P0847希望能解决这个问题