Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 创建类型副本_C++_C++11 - Fatal编程技术网

C++ 创建类型副本

C++ 创建类型副本,c++,c++11,C++,C++11,如何创建类型副本?例如,我如何创建类型质量、加速度和力,这些类型不能隐式转换为双精度(或任何其他数字类型),但具有双精度的所有特征。这将允许对该函数进行编译时输入有效性检查: Force GetForceNeeded(Mass m, Acceleration a); 确保只能使用类型为Mass和Acceleration的参数调用GetForceNeeded 当然,我可以通过手动创建以下类型的副本来实现: class Force final { public: //overload all op

如何创建类型副本?例如,我如何创建类型
质量
加速度
,这些类型不能隐式转换为
双精度
(或任何其他数字类型),但具有
双精度
的所有特征。这将允许对该函数进行编译时输入有效性检查:

Force GetForceNeeded(Mass m, Acceleration a);
确保只能使用类型为
Mass
Acceleration
的参数调用
GetForceNeeded

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

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

但这很麻烦。是否有一个通用的解决方案?

正如许多评论员所指出的,一个解决方案是使用提供问题中要求的所有功能的解决方案。下面是他们文档中的示例用法:

#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;
#包括
BOOST_STRONG_TYPEDEF(int,a)
空f(int x);//(1) 函数来处理简单整数
无效f(a x);//(2) 处理a型整数的特殊函数
int main(){
int x=1;
a y;
y=x;//根据需要转换作为a允许的其他操作
f(x);//选择(1)
f(y);//选择(2)
}类型定义INTA;
在C++1y中添加不透明的typedef有一个简单的方法


(我留下这个答案,因为我找不到确切的副本。如果不是,请标记。)

可能是模板?或者使用Boost.Units?@KerrekSB但如何公开所有定义的操作?假设我想为一个
字符串
?@Columbo正在读强typedef!这也许行。谢谢可以使用Typedefs。