简体   繁体   中英

C++ - is there any way to get the current executing line

I need to create an exception handling, in that I also asked to print the status of the operation like

"file open : The operation completed successfully"

"file close: The operation completed successfully",

etc.

Is there any macro for this like __LINE__,__FUNCTION__,__FILE__ ?

Or is there any boost function available to do this?

__LINE____FILE__在C ++中都可用,就像在C中一样。唯一的警告是它们是在编译时扩展的宏,因此,如果将它们放在宏或模板中,它们可能会或可能不会发挥您的期望。

I think the answer is that you want to stringify the expression you are evaluating?

Code:

#include <stdexcept>
#include <sstream>
#include <iostream>

void check_result(bool result, const char* file, int line_number, const char* line_contents)
{
    if (!result) {
        //for example:
        std::stringstream ss;
        ss << "Failed: " << line_contents << " in " << file << ' ' << line_number;
        throw std::runtime_error(ss.str());
    }
}

#define CALL_AND_CHECK(expression) check_result((expression), __FILE__, __LINE__, #expression)

bool foobar(bool b) { return b; }

int main()
{
    try {
        CALL_AND_CHECK(foobar(true));
        CALL_AND_CHECK(foobar(false));
    } catch (const std::exception& e) {
        std::cout << e.what() << '\n';
    }
}

I'm not sure what exactly you're asking but here is a code sample from my own library:

/**
 * \brief Convenient alias to create an exception.
 */
#define EXCEPTION(type,msg) type((msg), __FUNCTION__, __FILE__, __LINE__)

Basically, this allows me to write:

throw EXCEPTION(InvalidParameterException, "The foo parameter is not valid");

Of course here, InvalidParameterException is a class I designed that takes extra parameters to hold the function, the file and the line where the exception was created.

It has the following constructor:

InvalidParameterException::InvalidParameterException(
  const std::string& message,
  const std::string& function,
  const std::string& file,
  int line);

Of course, if you don't want to throw an exception but just output something to, say a logfile, you can obviously use the same "trick".

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM