你如何创建类型副本?例如,如何创建类型Mass,Acceleration以及Force哪些不是隐式转换为double(或任何其他数字类型),但除此之外的所有特征double.这将允许此函数的编译时输入有效性检查:
Force GetForceNeeded(Mass m, Acceleration a);
Run Code Online (Sandbox Code Playgroud)
确保GetForceNeeded只能使用类型Mass和参数调用Acceleration.
当然,我可以通过手动创建类型的副本来实现这一点:
class Force final
{
public:
//overload all operators
private:
double value;
};
Run Code Online (Sandbox Code Playgroud)
但这很麻烦.有通用的解决方案吗?
正如许多评论员所指出的,一种解决方案是使用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;
Run Code Online (Sandbox Code Playgroud)
有人建议将不透明的typedef添加到C++ 1y.
(我正在离开这个答案,因为我找不到确切的愚蠢.如果不是这样,请举报.)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |