user473973
user473973

Reputation: 711

Decltype in template parameter of variable

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?

Upvotes: 4

Views: 2859

Answers (1)

James McNellis
James McNellis

Reputation: 355357

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.)

Upvotes: 12

Related Questions