用函数替换宏

Replace macro with function

我有一段宏用来检查与 opengl 相关的错误

#if (GL_ERROR_CHECK == On)
#define GL_CHECK(x)                                                                                                    \
    x;                                                                                                                 \
    {                                                                                                                  \
        GLenum glError = glGetError();                                                                                 \
        if(glError != GL_NO_ERROR)                                                                                     \
        {                                                                                                              \
            std::cout << "GL Error: " << glError << " at " << __FILE__ << ", " << __LINE__ << std::endl;               \
        }                                                                                                              \
    }
#else
#define GL_CHECK(x)  x;
#endif

并这样使用它

GL_CHECK(glGenFramebuffers(1, (GLuint*)&m_u32FboID));
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_u32FboID));

我想知道是否有任何方法可以用适当的 c++ 函数替换此宏?

I am wondering if there is any way to replace this macro with a proper c++ function?

我认为宏在这种情况下是一个不错的选择。使用宏的主要好处之一是您可以使用 __FILE____LINE__ 作为消息的一部分。

您可以将一些代码移到函数中,但宏仍然有用。

void checkForError(char const* file, int line)
{
   GLenum glError = glGetError();
   if(glError != GL_NO_ERROR)
   {
      std::cout << "GL Error: " << glError << " at " << file << ", " << line << std::endl;
   }
}

#if (GL_ERROR_CHECK == On)
#define GL_CHECK(x) x; checkForError(__FILE__, __LINE__);
#else
#define GL_CHECK(x) x;
#endif

如果您使用的是 OpenGL 4.3 及更高版本,则可以改用调试回调,这样您就不必将每个 GL 函数都包装在宏中:Check it out here

启用一切:

glDebugMessageCallback(some_callback_function, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);

例如,这个函数:

void gl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity,
                       GLsizei length, const GLchar* message, const void* userParam)
{
    std::cerr << "GL Debug Message: " << message << '\n';
}

请注意,这有时会输出非错误的消息,因此您可以考虑打开严重性,或者对您使用 ...MessageControl 函数启用的内容进行更严格的限制。