2015-11-15 45 views
2

我對定義模板類的函數max有問題。在這堂課中,我們保留了一些不是簡單的整數,而是一些數字系統中的數字向量。並且,通過定義numeric_limits,我需要返回基於已定義數字系統的最大數字的表示形式。定義模板類的numeric_limits max函數

我得到很多錯誤,當我試圖返回類與最大表示法,但它的工作時返回整數。

我的模板類:

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

我已經試過這與常量,有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; 

這是我的任務,所以不要判斷方法做這件事,因爲這是我的老師選擇,我希望我提出了相當全面的問題。

回答

2

您面臨的問題是您嘗試將由max()函數返回的臨時文件綁定到輸出運算符的非const引用。

最乾淨的解決辦法是宣佈輸出操作爲:

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

和你output功能

void output(ostream& out) const 

注意,那我也刪除了output功能未使用的第二個參數。 const引用可以綁定到l值和r值,所以它也可以用於max()函數返回的臨時值。

編輯 As @ n.m。指出,你也不使用實際傳遞給operator <<的流,而只是使用std::cout。實現它的正確方法是簡單地用流(在你的情況下,只需更換cout << ...out << ...output功能這將讓語句,如std::cerr << std::numeric_limits<NSizeN<3> >::max();工作按預期

+0

得益於它完美的作品:。!。) – Yurrili

+0

如果仔細觀察,「輸出」的第一個參數如果還未使用。 –

+0

@ n.m。好點子。我會編輯答案。謝謝! – Rostislav