Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit variable template to a list of types

I'm trying to modernise some GStreamer code by adding smart pointers. So for instance:

GstElement *pipeline = gst_pipeline_new("test-pipeline");
gst_object_unref(pipeline);

can be rewritten:

struct GstElementDeleter {
    void operator()(GstElement* p) { gst_object_unref(p); }
};

std::unique_ptr<GstElement, GstElementDeleter> pipeline = gst_pipeline_new("test-pipeline");

But gst_object_unref() can be used on any gpointer so it can be rewritten:

template<typename T>
struct GPointerDeleter {
    void operator()(T* p) { gst_object_unref(p); }
};

std::unique_ptr<GstElement, GPointerDeleter<GstElement>> pipeline = gst_pipeline_new("test-pipeline");

But what I'd like to do is limit this to only handling types that can be deallocated using gst_object_unref. Is there a way of declaring a template to only work with a list of types - GstElement, GstBus, etc?

like image 236
parsley72 Avatar asked Oct 26 '25 07:10

parsley72


1 Answers

Maybe you could make template the operator() (so there is no need to explicit the template parameter defining the smart pointer) and use SFINAE to enable the operator() only for the allowed types

struct GPointerDeleter
 {
    template <typename T>
    typename std::enable_if<std::is_same<T, GstElement>::value
                         || std::is_same<T, GstBus>::value
                         /* or other cases */
             >::type operator() (T * p) const
     { gst_object_unref(p); }
 };

Or, maybe better, you can add (as suggested by Jarod42 (thanks)) a static_assert() check inside the operator()

struct GPointerDeleter
 {
    template <typename T>
    void operator() (T * p) const
     {
       static_assert( std::is_same<T, GstElement>::value
                   || std::is_same<T, GstBus>::value
                   /* or other cases */, "some error message" );

       gst_object_unref(p);
     }
 };
like image 80
max66 Avatar answered Oct 28 '25 22:10

max66



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!