【发布时间】:2013-09-08 08:31:44
【问题描述】:
我正在尝试实现一个template 类(名为Modular),以便进行一些模块化运算,例如求和和乘法。
int 和 int64_t 工作正常,但是如果我尝试传递诸如 int128_t 或 mpz_int 之类的 boost 整数类型,编译器会输出一些我不太了解的错误。
这是课程代码:
template <class T, int64_t modulus>
class Modular {
public:
Modular() : num_(0) { }
Modular(const T& num = 0) : num_(num % modulus) { }
Modular(const Modular& other) : num_(other.num_) { }
~Modular() { }
T get() const { return num_; }
Modular& operator=(const Modular& other) { num_ = other.num_; return *this; }
bool operator==(const Modular& other) { return num_ == other.num_; }
bool operator!=(const Modular& other) { return num_ != other.num_; }
Modular& operator++() { ++num_; num_ %= modulus; return *this; }
Modular operator++(int) { Modular temp(*this); operator++(); return temp; }
Modular& operator+=(const Modular& other) { num_ += other.num_; num_ %= modulus; return *this; }
Modular& operator-=(const Modular& other) { num_ -= other.num_; num_ %= modulus; return *this; }
Modular& operator*=(const Modular& other) { num_ *= other.num_; num_ %= modulus; return *this; }
Modular& operator/=(const Modular& other)
{
if((num_ % other.num_) == 0)
num_ /= other.num_;
else
{
Modular temp(0);
while(temp * other != num_)
++temp;
num_ = temp.num_;
}
return *this;
}
Modular pow(const T& exp)
{
if(exp == 1)
return *this;
Modular square(num_ * num_ % modulus);
if(exp & 1)
return (*this) * square.pow(exp/2);
else
return square.pow(exp/2);
}
protected:
T num_;
};
template <class T, T modulus>
inline Modular<T, modulus> operator+(const Modular<T, modulus>& lhs, const Modular<T, modulus>& rhs)
{
Modular<T, modulus> temp(lhs);
temp += rhs;
return temp;
}
template <class T, T modulus>
inline Modular<T, modulus> operator-(const Modular<T, modulus>& lhs, const Modular<T, modulus>& rhs)
{
Modular<T, modulus> temp(lhs);
temp -= rhs;
return temp;
}
template <class T, T modulus>
inline Modular<T, modulus> operator*(const Modular<T, modulus>& lhs, const Modular<T, modulus>& rhs)
{
Modular<T, modulus> temp(lhs);
temp *= rhs;
return temp;
}
template <class T, T modulus>
inline Modular<T, modulus> operator/(const Modular<T, modulus>& lhs, const Modular<T, modulus>& rhs)
{
Modular<T, modulus> temp(lhs);
temp /= rhs;
return temp;
}
这里是main():
#include <iostream>
#include <array>
#include <cstdint>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::int128_t;
int main()
{
const int128_t n = 123;
const int64_t mod = 456;
typedef Modular<int128_t, mod> mint;
const mint a = static_cast<int128_t)(789);
const mint b = static_cast<int128_t)(12);
mint result(0);
for(mint x(1); x != mint(101); ++x){
result += (a * x.pow(n+2) + b * x.pow(n+1) - x) / mint(x*x + x - mint(1));
}
std::cout << result.get();
return 0;
}
以及编译器输出:http://pastebin.com/1fNgDedt
最初我使用const int128_t mod,但编译器说mod必须定义constexpr所以我用它替换,但我不明白为什么,我完全不明白第一个编译器的错误。
【问题讨论】:
-
编译器似乎不认为
int128_t是一个整数类型。不知道为什么。
标签: templates boost c++11 constexpr