2015-10-21 24 views
0

我想重構在以下結構中的訪問器:重構讀寫訪問器從/到一個數據成員

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<class V = T> V get_val() { return V(val); }
  2. T& operator*() & { return val; }
  3. const T& operator*() const & { return val; }

現在我可以用這樣的方式(見註釋)的存取:

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; 
} 

現在是,吸氣更usueful?你在新界面中看到什麼奇怪的,不安全的或者違反直覺的東西(除了非向下兼容,我不關心)?

此外,我仍然有一個疑問是,如果最好通過返回V(val)V{val}val來實施get_val()。就像現在這樣,如果V有一個明確的構造函數,它就可以工作。你對這個問題有什麼看法?

+0

答案取決於'ValueTime'的目的,它仍然是神祕的。爲什麼不能使用'std'提供的功能? 'ValueTime'是否有更多的數據成員(原始代碼的評論中提到的'tp')是什麼? 'ValueTime :: val'的含義是什麼? – Walter

回答

0

我個人建議您儘可能使界面爲描述性,並避免任何方便轉換以引用數據或類似內容。 原因是簡單的可用性和維護。如果您或其他人使用ValueTime(重新)訪問代碼,當您不記得精確的界面時,您仍然想要了解您的代碼,而無需重新訪問ValueTime的定義。

成員來自std(如std::vector)的成員是有區別的,因爲你知道他們的定義。

相關問題