vendredi 30 octobre 2015

How to fix error refactoring decltype inside template

I'm passing a function into a template to become a pre-supplied argument to the constructor, but also need to use decltype on that function to pass the function type to unique_ptr<...> template instantiator(? is that the right word)

It works if I pre-use decltype as an extra template argument, but not if I invoke it inside the template on the function passed as a parameter.

I'm using g++ 4.9.2, and extending my explorations here Calling inherited template constructor of unique_ptr subclass where I subclass unique_ptr to have a fixed destructor, I find that some destructor functions do not return void, so I want a more generic template that does not need to specify the destructor function type.

My current code is:

void free_int(int* p) {
  delete p;
}

template<typename T, void (*D)(T*)>
class unique_dptr : public std::unique_ptr<T, decltype(D)> {
    public: unique_dptr(T* t) : std::unique_ptr<T, decltype(D)>(t, D) { };
};

using int_ptr = unique_dptr<int, ::free_int>;
int_ptr i(new int(2));

but note the void (*D)(T*) calling signature to restrict the destructor to a void function that takes a pointer to T

Given normal use of unique_ptr in this form:

unique_ptr<foo, decltype(&::free_foo)>

I want to have something like this:

template<typename T, typename D>
class unique_gptr : public std::unique_ptr<T, decltype(&D)> {
    public: unique_gptr(T* t) : std::unique_ptr<T, decltype(&D)>(t, D) { };
};

using int_gptr = unique_gptr<int, ::free_int>;
int_gptr ig(new int(2));

but the compiler hates it:

error: template argument 2 is invalid
class unique_gptr : public std::unique_ptr<T, decltype(&D)> {
                                                          ^

No doubt ancient C-macro style token pasting is what I am wrongly aiming at.

I have tried removing the & from decltype(&D) but that leaves the error:

error: argument to decltype must be an expression

however this is OK:

template<typename T, typename D, D F>
class unique_gptr : public std::unique_ptr<T, D> {
    public: unique_gptr(T* t) : std::unique_ptr<T, D>(t, F) { };
};

using int_gptr = unique_gptr<int, decltype(&::free_int), ::free_int>;
int_gptr ig(new int(2));

but I wonder what I am doing wrong that I can't manage move the decltype(&::free_int) into the template.


Other solutions

I realise that I can just write additional specialisations for other fixed free-function types, replacing void(*)(void*)

I realise that I can override the std::default_delete for my type.

But this is really an exercise in template composition

Aucun commentaire:

Enregistrer un commentaire