开发者

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?


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';
    }
}


Both __LINE__ and __FILE__ are available in C++, just like in C. The only caveat is that they are macros, expanded at compile-time, so if you stick them in macros or templates they may or may not do what you expect.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜