创建类型副本
Create type copies
如何创建类型副本?例如,我如何创建类型Mass
、Acceleration
和 Force
,这些类型不能隐式转换为 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;
有人提议将不透明的 typedefs 添加到 C++1y。
(我留下这个答案,因为我找不到确切的欺骗。如果不是这种情况,请标记。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 如何制作类型的副本?
- C 模板功能,相同类型,多个实例:共享一个相同的代码副本?即使在不同的CPP/对象文件中
- 推断类型,而浮动移动/副本无宏
- 创建类型副本
- visual返回C++中不完整类型的副本
- 如何在构造具有不同类型元素的向量副本时显式转换
- 为什么将CString类型转换为wchar_t*会产生一个临时副本?如果我们使用其他类型而不是CString呢?
- 类副本构造不能具有类类型的参数