2021年1月28日星期四

how to use lambda with templated std::unique_ptr?

NVIDIA objects such as nvinfer1::IRuntime and nvinfer1::ICudaEngine cannot be stored directly in a std::unique_ptr<>. Instead they have a destroy() method that must be called.

So to make this work, you must use a deleter like this:

#include <NvInfer.h>  #include <cuda.h>    template<typename T>  struct NVIDIADestroyer  {      void operator()(T * t)      {          t->destroy();      }  };    template<typename T>  using NVIDIAUniquePtr = std::unique_ptr<T, NVIDIADestroyer<T>>;  

Instead of std::unique_ptr<T>, you then use NVIDIAUniquePtr<T>.

So far, this works fine. What I then attempted to do while cleaning up the code is replace the deleter with a lambda so I could skip defining the NVIDIADestroyer structure. But I couldn't figure out how to do this. My thought was something along these lines:

template<typename T>  using NVIDIAUniquePtr = std::unique_ptr<T, [](T * t)  {      t->destroy();  }>;  

But this results in the following error messages:

TRT.hpp:52:45: error: lambda-expression in template-argument  using NVIDIAUniquePtr = std::unique_ptr<T, [](T * t)                                               ^  TRT.hpp:55:2: error: template argument 2 is invalid    }>;    ^  

Is there a way to make this work?

https://stackoverflow.com/questions/65938991/how-to-use-lambda-with-templated-stdunique-ptr January 28, 2021 at 10:21PM

没有评论:

发表评论