C++ convert int to string inline

barej

My problem seems to be very basic but I could not find a solution for it. I need to write a code which helps debugging by reporting the line and location of exception throwing. The problem is that __LINE__ is an int value and I have problem with its conversion into string in the following code where std::string(line) is used:

#pragma once

#include <stdexcept>
#include <cstring>


class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char * msg, const char * file,int line)
        :runtime_error(std::string(msg)+" @"+":"+std::string(line)){}
};

#define runtime_error_line(msg) CRuntime_error_line(msg,__FILE__,__LINE__)

Seems std::string(line) cannot convert int to string and other solutions suggested online cannot be implemented inline and I don't know how to call a base constructor in second line!

compiler output:

log.h: In constructor ‘CRuntime_error_line::CRuntime_error_line(const char*, const char*, int)’: log.h:10:124: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive] CRuntime_error_line(const char * msg, const char * file,int line):runtime_error(std::string(msg)+" @"+":"+std::string(line)){}

(Using g++ and linux environment)

edit:

the macro is supposed to be called this way:

throw runtime_error_line("Invalid somethihng ...!");
Jonathan Mee

As is suggested by Borgleader std::to_string is your solution. It will also construct a temporary std::string for you, so there's no need to construct a temporary string from msg:

#pragma once

#include <stdexcept>
#include <cstring>
#include <string> // Add this to support std::to_string


class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char* msg, const char* file, int line)
        : runtime_error(msg + " @:"s + std::to_string(line)){} // Use std::to_string here
};

#define runtime_error_line(msg) CRuntime_error_line(msg, __FILE__, __LINE__)

Without C++11 you can still do this it's just not as clean:

#pragma once

#include <stdexcept>
#include <cstring>
#include <sstream> // Use to include std::ostringstream    

class CRuntime_error_line: public std::runtime_error
{
public:
    CRuntime_error_line(const char* msg, const char* file, int line)
        : runtime_error(static_cast<std::ostringstream&>(std::ostringstream() << msg << " @:" << line).str()){} // Use std::ostringstream here
};

#define runtime_error_line(msg) CRuntime_error_line(msg, __FILE__, __LINE__)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related