Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decltype in template parameter of variable

Tags:

c++

c++11

I'm working on some code with unique_ptrs and the like. The line is:

std::unique_ptr<char[], void(*)(void*)> result(..., std::free);

which works. I realize that the type that std::free gives is that second template parameter. I tried using:

std::unique_ptr<char[], decltype(std::free)> result(..., std::free);

which would be easier to read and less bug-prone. But I get errors related to <memory> and "instantiating a data member with a function type".

Would there be a way to do this?

like image 375
user473973 Avatar asked Dec 15 '22 03:12

user473973


1 Answers

decltype(std::free) yields the type of std::free, which is the function type void(void*), not the function pointer type void(*)(void*). You need a function pointer type, which you can obtain by taking the address of std::free:

std::unique_ptr<char[], decltype(&std::free)> result(..., std::free);
                               ^

or by forming the function pointer type yourself:

std::unique_ptr<char[], decltype(std::free)*> result(..., std::free);
                                         ^

(I'd argue that the former is clearer.)

like image 137
James McNellis Avatar answered Dec 27 '22 10:12

James McNellis