【发布时间】: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 数据成员的访问器更有用和更直观,主要是从代表“时间价值”的这种结构的“标准/提高用户期望”的角度来看:
template<class V = T> V get_val() { return V(val); }T& operator*() & { return val; }const T& operator*() const & { 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是什么意思?