创建类型副本

Create type copies

本文关键字:副本 类型 创建      更新时间:2023-10-16

如何创建类型副本?例如,我如何创建类型MassAccelerationForce,这些类型不能隐式转换为 double(或任何其他数值类型),但在其他方面具有double的所有特征。这将允许对此函数进行编译时输入有效性检查:

Force GetForceNeeded(Mass m, Acceleration a);

确保只能使用 MassAcceleration 类型的参数调用GetForceNeeded

当然,我可以通过手动创建该类型的副本来实现这一点:

class Force final
{
public:
//overload all operators
private:
double value;
};

但这很麻烦。有通用解决方案吗?

正如许多评论员所指出的那样,一种解决方案是使用BOOST_STRONG_TYPEDEF,它提供了问题中要求的所有功能。这是他们文档中的示例用法:

#include <boost/serialization/strong_typedef.hpp>

BOOST_STRONG_TYPEDEF(int, a)
void f(int x);  // (1) function to handle simple integers
void f(a x);    // (2) special function to handle integers of type a 
int main(){
    int x = 1;
    a y;
    y = x;      // other operations permitted as a is converted as necessary
    f(x);       // chooses (1)
    f(y);       // chooses (2)
}    typedef int a;

有人提议将不透明的 typedefs 添加到 C++1y。

(我留下这个答案,因为我找不到确切的欺骗。如果不是这种情况,请标记。