这是我的断言函数(它不会编译“error C2110: '+' : cannot add two pointers”):
#define CHAR(x) #x
template<typename T>
inline void ASSERT(T x)
{
if(!x)
{
std::string s("ERROR! Assert " + CHAR(x) + " failed. In file " + __FILE__ +
" at line " + __LINE__ + ".");
std::wstring temp(s.length(), L' ');
std::copy(s.begin(), s.end(), temp.begin());
getLogger().Write(temp);
}
}
知道如何解决吗?
最佳答案
字符串文字很容易简化为 char
指针,当您尝试使用 "ERROR! Assert "+ CHAR(x) + "failed. In file "时,无法添加指针。 ..
。但是,C++ 具有在编译前自动执行此操作的便捷功能! (预处理器执行此操作)。更好的是,它有一个方便的工具,可以在编译时生成宽字符串。所以,你想要:
#define _T(x) L ## x
#define CHAR(x) #x
#define CHAR2(x) CHAR(x)
#define ASSERT(x) ASSERT2(x, CHAR(x), __FILE__, CHAR2(__LINE__))
#define ASSERT2(x, t, f, l) \
if(!x) \
getLogger().Write(L"ERROR! Assert " _T(t) L" failed. In file " _T(f) L" at line " _T(l) L".");
关于c++ - 无法创建断言函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438329/