簡體   English   中英

如何在c ++函數模板中指定默認的非模板參數初始值設定項?

[英]How do I specify default non-template argument initializers in a c++ function template?

編輯:有關詳細信息,請參閱我自己對此問題的回答。 事實證明這是一個Eclipse Juno錯誤,而不是C ++問題。 盡管如此,該問題仍然涵蓋了其他C ++模板用戶的有用主題。

如果我希望創建一個模板類,其參數為“template”類型,其他參數為“non-temlate”類型,我可以指定嗎?

示例:一個實現或itoa()但有多個類型,填充和返回一個字符串......

編輯:定義中的固定var名稱。

   template <typename T>   std::string    Num2Str( T x, char pad = ' ', int width = 0 );
   template <typename T>   std::string    Num2Str( T x, char pad, int width )
   {
      static std::string   string;
      std::stringstream    ss;
      ss << std::setfill(pad) << std::setw(width) << x;
      string = ss.str();
      return string;
   }

編輯:這應該適用於編譯器/平台,g ++,VC ++。

我認為你正在混合模板參數和函數參數。 為什么不這樣:

#include <sstream>
#include <iomanip>

template <typename T>   
std::string Num2Str( T x, char pad = ' ', int width = 0 )
{
    static std::string   string;
    std::stringstream    ss;
    ss << std::setfill(pad) << std::setw(width) << x;
    string = ss.str();
    return string;
}

void Test()
{
    auto s1 = Num2Str( 1.0 );
    auto s2 = Num2Str( 2, '-' );
    auto s3 = Num2Str( 3.0, ' ', 3 );
}

好吧,我發現了這個bug。 語法或C ++絕對沒有。 這是Eclipse Juno中的一個錯誤。 索引器似乎跟不上構建。 重建索引擺脫了兩個錯誤。 Project Expolrer->(projname)->Index->Rebuild 您可能首先需要執行Project Expolrer->(projname)->Index->Freshen All Files 最后,在Problems窗格中,按ctrl-A選擇所有錯誤然后delENTER清除錯誤日志。

這個索引器錯誤的有趣工件是IDE在當前構建之前並不總是忘記它知道的錯誤。 它似乎無法忘記上述兩個錯誤並報告它們即使它們不在那里!

我將編輯OP以添加“Ecipse Juno”作為標簽,希望它能幫助該組中的某個人。

感謝您的幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM