Advertisement
Guest User

My trick for common GL error handling

a guest
Mar 13th, 2012
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. // Thanassis Tsiodras, Dr.-Ing
  2. // My C++11 trick for common GLerror handling (regardless of whether the API returns something or not)
  3. // March 13, 2012
  4.  
  5. // User code:
  6.    ...
  7.    // this API (glCreateShader) returns something
  8.    shader_ = GLERROR(glCreateShader(VertexShader==shaderType?GL_VERTEX_SHADER:GL_FRAGMENT_SHADER));
  9.    // this (glShaderSource) doesn't
  10.    GLERROR(glShaderSource(shader_, 1, &pShaderCode, NULL));
  11.    // neither does this (glCompileShader)
  12.    GLERROR(glCompileShader(shader_));
  13.    ...
  14.  
  15. // Library code: how I did it with lambdas and std::function
  16.  
  17. void commonCode(const char *file, size_t lineno) {
  18.     GLenum err = glGetError();
  19.     if (err != GL_NO_ERROR) {
  20.         while (err != GL_NO_ERROR) {
  21.             std::cerr <<
  22.                 "glError: " << (char *)gluErrorString(err) <<
  23.                 " (" << file << ":" << lineno << ")" << std::endl;
  24.             err = glGetError();
  25.         }
  26.         throw "Failure in GLSL...";
  27.     }
  28. }
  29.  
  30. template <class T>
  31. auto glError(std::function<T()>&& t, const char *file, size_t lineno) -> decltype(t()) {
  32.     auto ret = t();
  33.     commonCode(file,lineno);
  34.     return ret;
  35. }
  36.  
  37. template<>
  38. void glError(std::function<void(void)>&& t, const char *file, size_t lineno) {
  39.     t();
  40.     commonCode(file,lineno);
  41. }
  42.  
  43. template <class T>
  44. auto helper (T&& t) -> std::function<decltype(t())()>
  45. {
  46.     std::function<decltype(t())()> tmp = t;
  47.     return tmp;
  48. }
  49.  
  50. #define GLERROR( expr ) \
  51.     [&]() { \
  52.         return glError( helper( [&]() { return expr; } ),  __FILE__, __LINE__); \
  53.     }()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement