我目前正在阅读 Scott Meyers 的《Effective C++》一书。它说我应该更喜欢inline
功能超过#define
对于类似函数的宏。
现在我尝试编写一个内联函数来替换我的异常宏。我的旧宏看起来像这样:
#define __EXCEPTION(aMessage) \
{ \
std::ostringstream stream; \
stream << "EXCEPTION: " << aMessage << ", file " <<__FILE__ << " line " << __LINE__; \
throw ExceptionImpl(stream.str()); \
}
我的新内联函数是这样的:
inline void __EXCEPTION(const std::string aMessage)
{
std::ostringstream stream;
stream << "EXCEPTION: " << aMessage << ", file " <<__FILE__ << " line " << __LINE__;
throw ExceptionImpl(stream.str());
}
正如一些人可能已经预料到的那样,现在__FILE__
and __LINE__
宏是无用的,因为它们总是引用带有内联函数定义的 C++ 文件。
有什么方法可以避免这种行为还是我应该坚持使用旧的宏?我在这里阅读了这篇文章,我已经怀疑我的第二个例子可能无法正常工作:
- 内联函数中 __LINE__ 的行为
- C++ 中的 __FILE__、__LINE__ 和 __FUNCTION__ 用法
不要使用__
(双下划线)因为它是保留的。拥有一个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());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)