C++中是否有可能使" "过载?
Is it possible to overload "" in C++?
我的意图是实现一个大整数类。
如果我试图给一个对象赋值,它必须以这种方式完成
Big_int n =1234567890123456;
而不是以这种方式
Big_int n ="1234567890123456";
最好使用用户定义的文字。自C++11以来,它们在C++中可用。为了接受任意长的数字序列,您需要使用接受const char*
的文字函数。
以下代码为您提供了用户定义文字所需内容的草稿:
#include <iostream>
#include <string>
class BigInt {
const std::string str;
BigInt(const std::string& s) : str(s) { }
friend BigInt operator "" _bi(const char* s);
friend std::ostream& operator<<(std::ostream& os, const BigInt& bi);
};
BigInt operator "" _bi(const char* s) {
return BigInt(s);
}
std::ostream& operator<<(std::ostream& os, const BigInt& bi) {
return os << bi.str;
}
int main() {
BigInt bi1 = 123_bi;
BigInt bi2 = 123123412345123456123456712345678_bi;
//BigInt bi3 = std::string("123");
std::cout << bi1 << ' ' << bi2;
return 0;
}
文字运算符函数operator ""
接受字符串文字。我让它成为BigInt类的朋友,所以接受字符串的构造函数对您类的用户不可用,但您可以使用带有_bi
后缀的数字序列。唯一的缺点是带有const char*
参数的文字运算符函数是整数和浮点文字的回退函数,因此仍然可以使用之类的函数
BigInt bi = 123.45_bi;
要阻止它,您可以声明额外的
class Dummy {};
Dummy operator "" _bi(long double d) {
return Dummy();
}
假设您的BigInt类不能用Dummy
初始化,如果您尝试将BigInt与浮点_bi
文字一起使用,则这将是一个编译时错误。
您需要添加一个后缀。
C++不允许自定义解析规则,因此除非添加(可能是自定义的)后缀,否则无法处理很大的数字。
不能说"如果数字对于标准整数的精度来说太多,就使用这个类"。
下面是我如何解决这个问题的开始。
c++14的constexpr意味着所有操作都可以在编译时完成,因此(相当好的)可读性不需要付出性能成本。
#include <iostream>
#include <cmath>
#include <cassert>
struct big_int {
constexpr big_int(int x = 0) {}
constexpr big_int(std::initializer_list<int> il)
: big_int(0)
{
for (int i : il) {
assert(i < 1000);
assert(i >= 0);
(*this) *= 1000;
(*this) += i;
}
}
// todo - add implementation here
constexpr big_int& operator*=(int i) { return *this; }
constexpr big_int& operator+=(int i) { return *this; }
// todo - data structure here
};
int main()
{
using namespace std;
auto bi = big_int({123, 456, 789, 98, 765, 654}); // care: missing leading zero!
return 0;
}
相关文章:
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 有可能使shared_ptr协变吗
- 有可能在信号处理程序中设置promise吗
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 是否有可能构建面向Linux和Windows的.Net Core C++ / CLI应用程序?
- 是否有可能使用debug_info获取ELF文件的源代码?
- C++,是否有可能/如何定义在.h和.cpp源文件中调用函数的类构造函数
- 有可能在C++中有类的查找表吗
- 是否有可能让 c++ dll 在后台运行 python 程序并让它填充向量图?如果是这样,如何?
- 向量的大小是否有可能为 1 但其中的元素数量为零?
- 是否有可能编写新的叮当声现代化规则?
- 是否有可能通过指向另一个未关联的子对象的指针来获取指向一个子对象的指针?
- 是否有可能通过演绎指南实现整个 std::make_tuple 功能?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 是否有可能具有放入容器的移动操作的类型?
- 是否有可能通过溢出 C 中的第一个元素来写入数组第二个元素
- 声明是否有可能逃脱其封闭的名称空间
- git-是否有互联网上某处所有可能错误的列表
- C++中是否有可能使" "过载?