如何用支持__LINE__和__FILE__的内联函数替换我的c ++异常宏?

Joh*_*ohn 5 c++ macros inline exception c-preprocessor

我目前正在阅读Scott Meyers的"Effective C++"一书.它说我应该更喜欢inline功能#define类似功能的宏.

现在我尝试编写内联函数来替换我的异常宏.我的旧宏看起来像这样:

#define __EXCEPTION(aMessage) \
{ \
    std::ostringstream stream; \
    stream << "EXCEPTION: " << aMessage << ", file " <<__FILE__ << " line " << __LINE__; \
    throw ExceptionImpl(stream.str()); \
}
Run Code Online (Sandbox Code Playgroud)

我的新内联函数是这样的:

inline void __EXCEPTION(const std::string aMessage)
{
   std::ostringstream stream;
   stream << "EXCEPTION: " << aMessage << ", file " <<__FILE__ << " line " << __LINE__;
   throw ExceptionImpl(stream.str());
}
Run Code Online (Sandbox Code Playgroud)

正如一些人可能已经预料的那样,现在__FILE____LINE__宏都没用了,因为它们总是引用带有内联函数定义的C++文件.

有没有办法规避这种行为,还是应该坚持我的旧宏?我在这里阅读了这些帖子,我已经怀疑我的第二个例子可能无法正常工作:

iam*_*ind 19

不要使用__(双下划线),因为它是保留的.有一个inline功能更好.
但是,这里需要混合使用宏和函数,因此您可以执行以下操作:

#define MY_EXCEPTION(aMessage) MyException(aMessage, __FILE__, __LINE__) 

inline void MyException(const std::string aMessage,
                        const char* fileName,
                        const std::size_t lineNumber)
{
   std::ostringstream stream;
   stream << "EXCEPTION: " << aMessage << ", file " << fileName << " line " << lineNumber;
   throw ExceptionImpl(stream.str());
}
Run Code Online (Sandbox Code Playgroud)