Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Error: use of undeclared identifier: exception in template class



  • I would like to create this template class:

    #include <sstream>
    #include <string>
    #include <exception>
    
    template<class T>
    std::string ToStr(const T &value)
    {
      std::ostringstream oss;
      if (!(oss << std::dec << value)) throw exception("Invalid argument");
      return oss.str();
    }
    

    But I get the following compiler error:

    error: use of undeclared identifier 'exception'
    .../conversions.h:41: Fehler: there are no arguments to ‘exception’ that depend on a template parameter, so a declaration of ‘exception’ must be available [-fpermissive]
       41 |   if(!(iss>>std::dec>>result))throw exception("Invalid argument");
          |                                     ^~~~~~~~~
    

    How do I have to handle that?


  • Qt Champions 2019

    @Infinity said in Error: use of undeclared identifier: exception in template class:

    How do I have to handle that?

    There is no class 'exception' somewhere. It's maybe std::exception what you're looking for.



  • I found the solution:

    #include <sstream>
    #include <string>
    #include <exception>
    
    class MyException : public std::exception
    {
        virtual const char* what() const throw() {
            return "Invalid argument";
        }
    };
    
    MyException myException;
    
    //---------------------------------------------------------------------------
    // Convert a number to a string
    
    template<class T>
    std::string NumberToStr(const T &value)
    {
        std::ostringstream oss;
        if (!(oss << std::dec << value)) throw myException;
        return oss.str();
    }
    

Log in to reply