您如何创建活字拷贝?例如,我如何创建不能隐式转换为 double
(或任何其他数字类型),但在其他方面具有 double
的所有特征。这将允许对此函数进行编译时输入有效性检查:
Force GetForceNeeded(Mass m, Acceleration a);
确保只能使用 Mass
和 Acceleration
类型的参数调用 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;
有一个proposal向 C++1y 添加不透明的 typedef。
(我要留下这个答案,因为我找不到确切的骗子。如果不是这种情况,请标记。)
关于c++ - 创建类型拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27693122/