gpt4 book ai didi

C++ "unsigned"类

转载 作者:太空狗 更新时间:2023-10-29 20:37:02 26 4
gpt4 key购买 nike

我正在编写一些用于处理小数数据(与 float 据相对)的目标代码,到目前为止有以下内容:

 class frac {
public:
int numerator;
unsigned int denominator;
};

我的问题是:
我如何配置我的类定义以便编写 unsigned frac foo;使对象与 frac foo; 相同, 除了 int numerator;会变成unsigned int numerator;

编辑:虽然通常我只使用模板 ( frac <unsigned> ),但这段代码将进入更大的数学 API,我更希望最终产品使用 unsigned frac句法

扩展名:许多答案都表明不可能实现 unsigned frac语法,但有谁知道为什么不呢? C++ 编译器是否有一些特殊的处理规则来适应现有的 unsigned类型,还是我还缺少其他东西?

最佳答案

您可以使用模板实现这些目标。例如

template <class Integral>
class frac {
public:
Integral numerator;
std::make_unsigned_t<Integral> denominator;
};

http://en.cppreference.com/w/cpp/types/make_unsigned

你可以像这样使用这个类:

frac<int> signed;
frac<unsigned> nonnegative;

关于C++ "unsigned"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com