代码之家  ›  专栏  ›  技术社区  ›  rkellerm

stringstream operator<<对于模板类型

  •  3
  • rkellerm  · 技术社区  · 15 年前

    我有以下代码:

    template <class T>
    static std::string ToString(const T& t)
    {
      stringstream temp;
      temp << t;
      return temp.str();
    }
    

    它编译Windows上没有VisualC++的问题,但是当尝试用GCC在Linux上编译时,我得到以下错误:

    no match for 'operator<<' in 'temp << t'
    

    为什么会这样?

    提前谢谢。

    2 回复  |  直到 12 年前
        1
  •  4
  •   Prasoon Saurav    15 年前

    这取决于T型,正如太空人所说。

    查看以下代码

    #include <sstream>
    #include <iostream>
    
    template<typename T>
    static std::string ToString(const T& t){
      std::stringstream temp;
      temp << t;
      return temp.str();
    }
    struct empty{};
    struct non_empty{
      std::string str;
      non_empty(std::string obj):str (obj){}
      friend std::ostream& operator << (std::ostream& out, const non_empty &x);
    };
    
    std::ostream& operator << (std::ostream& out, const non_empty &x){
        out << x.str;
        return out;
    }
    
    int main(){
       std::string s = ToString<double>(12.3); // this will work fine
     /*********************************************************************************
      * std::string k = ToString(empty()); // no match for 'operator<<' in 'temp << t'*
      *********************************************************************************/
       std::string t = ToString(non_empty("123")); // this works too
    
    }
    

    呼叫 ToString(empty()); 给你同样的错误,但是 ToString(non_empty("123")); fine . 这意味着什么?

        2
  •  0
  •   Panda saeed    12 年前

    你可能只是错过了 #include<sstream> 从文件的顶部。

    这可以解释为什么相同的代码可以在Windows上编译,因为标准头文件之间存在差异。

    在我的案例中,这是在使用模板时 const char* .