【问题标题】:Refactoring read write accessors from/to one data member从/向一个数据成员重构读写访问器
【发布时间】:2016-01-20 07:56:57
【问题描述】:

我想重构以下结构的访问器:

template<class T>
class ValueTime {
public:
   // accessors for val:
   const T& get_val() const { return val; }
   template<class V> void set_val(const V& v) { val = v; }
   // other accessors for tp

private:
   T val;
   std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
};

我想让val 数据成员的访问器更有用和更直观,主要是从代表“时间价值”的这种结构的“标准/提高用户期望”的角度来看:

  1. template&lt;class V = T&gt; V get_val() { return V(val); }
  2. T&amp; operator*() &amp; { return val; }
  3. const T&amp; operator*() const &amp; { return val; }

现在我可以通过这种方式使用访问器(参见 cmets):

int main() {
    ValueTime<double> vt;

    // get_val() no longer returns const ref and also
    // allows explicit cast to other types
    std::chrono::minutes period{vt.get_val<int>()}; // I had to use the more pedantic static_cast<int> with the original version

    // let's use operator*() for getting a ref.
    // I think that for a structure like a ValueTime structure,
    // it's clear that we get a ref to the stored "value"
    // and not to the stored "time_point"
    auto val = *vt; // reference now;
    val = 42;
}

getter 现在更常用了吗?您是否在新界面中看到任何奇怪、不安全或违反直觉的东西(除了不向后兼容,我不在乎)?

此外,我还有一个疑问是通过返回 V(val)V{val} 或仅返回 val 来实现 get_val() 是否更好。就像现在一样,如果 V 有一个显式的构造函数,它就可以工作。你怎么看这个问题?

【问题讨论】:

  • 答案取决于ValueTime 的目的,这仍然是个谜。为什么不能使用std 提供的功能? ValueTime 是否有更多的数据成员(原代码注释中提到的tp 是什么)? ValueTime::val是什么意思?

标签: c++ c++11 boost std


【解决方案1】:

我个人会建议您使界面尽可能描述性,并避免任何方便的转换为数据引用或类似内容。 原因只是可用性和维护。如果您或其他人正在(重新)使用ValueTime 访问代码,当您不记得确切的接口时,您仍然希望在不重新访问ValueTime 的定义的情况下理解您的代码。

std(如std::vector)的成员不同的是,您对他们的定义了如指掌。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多