c++ - 无法创建断言函数

标签 c++

这是我的断言函数(它不会编译“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".");

http://ideone.com/0ibcj

关于c++ - 无法创建断言函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438329/

相关文章:

c# - 谁知道mc.exe(Message Compiler)怎么用?

c++ - C++/CLI 中的简单 MEF 示例

c++ - Qt 如何添加到 Windows 标题栏?

c++ - vector<T>::push_back 用于预定义的构造函数?

带 header 的 C++ 委托(delegate)构造函数

c++ - 这个 GNU 对三元运算符的扩展有多广泛?

c++ - Lua语法错误的描述性错误消息

c++ - (避免)在 C++ 中将代码拆分为 .cpp 和 .h 并进行高效编译

c++ - 编辑数组以确保严格增加值

c++ - `int` 与 `double` 的问题 - 为什么我的程序不工作?