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
數據成員更加有用和直觀的,大多是從的鑑於這樣的結構的「標準/升壓用戶期望」表示「在時間價值」的點:
template<class V = T> V get_val() { return V(val); }
T& operator*() & { return val; }
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有一個明確的構造函數,它就可以工作。你對這個問題有什麼看法?
答案取決於'ValueTime'的目的,它仍然是神祕的。爲什麼不能使用'std'提供的功能? 'ValueTime'是否有更多的數據成員(原始代碼的評論中提到的'tp')是什麼? 'ValueTime :: val'的含義是什麼? – Walter