我正在编写一些代码来帮助我更好地处理单元,方法是让用户为诸如Metres、Centimetres和Millimetres这样的东西定义一个类型。下面是Metres的类声明:
template <typename StorageType>
class Metres : public Unit<StorageType>
{
public:
static Metres fromMetres (StorageType metres) noexcept;
Metres operator+ (Metres rhs) const noexcept;
Metres operator+ (Centimetres<StorageType> rhs) const noexcept;
Metres operator+ (Millimetres<StorageType> rhs) const noexcept;
protected:
using Unit<StorageType>::Unit;
};然而,在编写operator+函数的定义时,我发现自己经常重复Metres<StorageType>:
template <typename StorageType>
Metres<StorageType> Metres<StorageType>::fromMetres (StorageType metres) noexcept
{ return { metres }; }
template <typename StorageType>
Metres<StorageType> Metres<StorageType>::operator+ (Millimetres<StorageType> rhs) const noexcept
{ return { this->getRawValue() + rhs.getRawValue() / StorageType (1000) }; }
template <typename StorageType>
Metres<StorageType> Metres<StorageType>::operator+ (Centimetres<StorageType> rhs) const noexcept
{ return { this->getRawValue() + rhs.getRawValue() / StorageType (100) }; }
template <typename StorageType>
Metres<StorageType> Metres<StorageType>::operator+ (Metres<StorageType> rhs) const noexcept
{ return { this->getRawValue() + rhs.getRawValue() }; }我不能像Centimetres和Millimetres转发声明的那样在类声明中定义函数。如果我事先定义了这些类,我就会在不同的类中得到相同的问题。
我觉得这样可以做得更好。如何减少这些函数定义中的视觉噪声量?
注意:如果C++中有任何规则允许在某些地方省略<StorageType>,则非常感谢标准中的引号。
发布于 2015-10-30 23:28:20
显而易见的可能性是只定义类定义中的函数:
template <typename StorageType>
class Metres : public Unit<StorageType> {
public:
static Metres fromMetres(StorageType metres) noexcept { return metres; }
Metres operator+ (Metres rhs) const noexcept {
return getRawValue() + rhs.getRawValue();
}
Metres operator+ (Centimetres<StorageType> rhs) const noexcept {
getRawValue() + rhs.getRawValue() / StorageType(100);
}
Metres operator+ (Millimetres<StorageType> rhs) const noexcept {
getRawValue() + rhs.getRawValue() / StorageType(1000);
}
protected:
using Unit<StorageType>::Unit;
};问题(无论如何,在我看来)来自两个事实:这些都是模板,所以您需要包含模板参数,而所讨论的函数的主体非常小,它们基本上在噪音中消失了。
这两种情况都说明了这样一个事实:(在本例中),类定义中内联的函数定义获得了很大的收益,而且没有损失。
https://codereview.stackexchange.com/questions/109323
复制相似问题