标记类以禁止操作

  • 本文关键字:禁止 操作 c++ c++11
  • 更新时间 :
  • 英文 :


我希望能够使用编译时信息来防止同一类的两个对象被组合。特别是如果a表示米,而b使用厘米,我希望编译器不允许它们的组合。

我可以使用受保护的继承来执行此操作吗?我需要使用标签吗?

像这样的东西?

struct Meters{};
struct Centimeters{};
template < typename Units >
class DimensionedLength : protected Length {
// What do I need to put in here?
}
int main(){
{
Length a(0.0), b(1.0), c(2.0);
std::cout << a+b << std::endl; // fine
std::cout << a+c << std::endl; // fine
}

{
DimensionedLength<Meters> a(0.0), b(1.0);
DimensionedLength<Centimeters> c(2.0);
std::cout << a+b << std::endl; // fine
std::cout << a+c << std::endl; // compile error!
}
return 1;
}

首先,类模板应如下所示:

template<typename Units>
struct DimensionedDouble {
double value;
};

然后你需要为它实现所有的算术运算符,即:

template<typename Units>
DimensionedDouble<Units> operator+(DimensionedDouble<Units> x, DimensionedDouble<Units> y) {
return {x.value + y.value};
}

等等。重载只能在Units匹配时调用,否则会出现错误。

根据您希望获得语法与基本类型的接近程度,您可能还希望将double等构造函数添加到您的类中。如上所示,只能从double(使用{...}= {...}(进行聚合初始化。

最新更新