为template类定义numeric_limits-max函数

defining numeric_limits max function for template class

本文关键字:limits-max 函数 numeric 定义 template      更新时间:2023-10-16

我在为模板类定义函数max时遇到问题。在这个类中,我们把一个数保持为不是简单的整数,而是一些数字系统中的数字向量。通过定义numeric_limits,我需要返回建立在定义的数字系统上的最大数的表示。

当我试图返回具有最大表示的类时,我会遇到很多错误,但当返回integer时它会起作用。

我的模板类:

template<int n,typename b_type=unsigned int,typename l_type=unsigned long long,long_type base=bases(DEC)>
class NSizeN
{
  public:
    int a_size = 0; 
    vector <b_type> place_number_vector; // number stored in the vector
    NSizeN(int a){ //constructor
        do {
            place_number_vector.push_back(a % base);
            a /= base;
            a_size ++;
        } while(a != 0);
    }
    void output(ostream& out, NSizeN& y)
    {
        for(int i=a_size - 1;i >= 0;i--)
        {
            cout << (l_type)place_number_vector[i] << ":";
        }
    }
    friend ostream &operator<<(ostream& out, NSizeN& y)
    {
        y.output(out, y);
        return out << endl;
    }
}

在.h文件的末尾,我有这样的:

namespace std{
template<int n,typename b_type,typename l_type,long_type base>
class numeric_limits < NSizeN< n, b_type, l_type, base> >{
public :
     static NSizeN< n, b_type, l_type, base> max(){
        NSizeN< n, b_type, l_type, base> c(base -1); 
        return c;
     }
}

我已经用const和constexpr尝试过了,但它不起作用。我不知道如何消除这些错误:

error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to'std::basic_ostream<char>&&'
 std::cout << std::numeric_limits<NSizeN<3> >::max() << endl;
error:   initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = NSizeN<3>]'
 operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

这就是我主要想做的:

    std::cout << std::numeric_limits<NSizeN<3> >::max() << endl;

这是我的作业,所以不要评判做这件事的方式,因为这是我老师的选择,我希望我能比较全面地提出我的问题。

您面临的问题是,您试图将max()函数返回的临时绑定到输出运算符的非常数引用。

最干净的解决方案是将输出运算符声明为:

friend ostream &operator<<(ostream& out, const NSizeN& y)

并且您的output功能为

void output(ostream& out) const

注意,我还删除了output函数未使用的第二个参数。const引用可以绑定到l值和r值,因此它也适用于max()函数返回的临时值。

编辑正如@n.m.所指出的,您也不使用实际传递给operator <<的流,而只使用std::cout。实现它的正确方法是简单地使用流(在您的情况下,只需在output函数中将cout << ...替换为out << ...。这将使std::cerr << std::numeric_limits<NSizeN<3> >::max();等语句按预期工作。