C++中是否有可能使" "过载?

Is it possible to overload "" in C++?

本文关键字:过载 有可能 是否 C++      更新时间:2023-10-16

我的意图是实现一个大整数类。

如果我试图给一个对象赋值,它必须以这种方式完成

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;
}