1

I have a macro:

#define checkAlloc(ans)  checkPointer((ans), __FILE__, __LINE__); 

which is used to wrap around any pointer allocation to check it is valid (used for checking memory allocations on a GPU device side).

The macro is used as follows:

SomeObject* myObj = checkAlloc(new SomeObject());

and the checkPointer function is implemented as:

inline __device__ SomeObject* checkPointer(SomeObject* pointer, char *file, int line)
{
    if (pointer == nullptr)
    {
        // do error logging
    }
    return pointer;
}

Now, it is very inconvenient to create a new version of the function for each type of object I might allocate to. Templates are also not an option since I would like syntax to be clear - i.e. just putting checkAlloc(…) around each allocation rather than checkAlloc<SomeObject>(…) which is ugly and hopefully unnecessary.

Ideally I would like to change the checkPointer to be:

inline __device__ auto checkPointer(auto pointer, char *file, int line)

but I understand auto cannot be used for a function parameter yet. The GPU code supports C++14 so lambdas could be used as a potential workaround from I can read at https://stackoverflow.com/a/29945034/7283981 but I am not familiar enough with lambdas to know how to do this. Any ideas?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

3

This is the perfect case for a template, I don't understand why you are trying to avoid it:

template < typename T >
inline __device__ T* checkPointer(T* pointer, const char *file, int line)
{
  if (pointer == nullptr)
  {
    // do error logging
  }

  return pointer;
}

This is very clear and clean and you can use it as if there was an auto there:

int main(int argc, char** argv)
{
    SomeObject* myObj = checkAlloc(new SomeObject());
}

As you can see, there are automatic argument deduction capabilities that don't even require any type specification...

Oh, and notice that I changed char * file to const char * file as C++11 doesn't allow conversion of literals to char *

Daniel Trugman
  • 8,186
  • 20
  • 41