【发布时间】:2019-12-26 12:23:03
【问题描述】:
我希望能够使用编译时间信息来防止合并同一类的两个对象。特别是如果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;
}
【问题讨论】: