c++ - Pass container of raw pointers and smart pointers to template function -


is there possibility abstract pointer type of objects container when container (e.g.: std::vector) passed function template?

i have following 2 methods:

template <typename t, typename alloct, template <typename, typename> class containert> static void parse(containert<t *, alloct> &entries, const rapidjson::value &jsondocument) {     (rapidjson::sizetype entryit = 0; entryit < jsondocument.size(); ++entryit)     {         entries.push_back(new t());         entries[entryit]->parse(jsondocument[entryit]);     } } 

and

template <typename t, typename alloct, template <typename, typename> class containert> static void parse(containert<std::unique_ptr<t>, alloct> &entries, const rapidjson::value &jsondocument) {     (rapidjson::sizetype entryit = 0; entryit < jsondocument.size(); ++entryit)     {         entries.push_back(std::move(std::unique_ptr<t>(new t())));                     entries[entryit]->parse(jsondocument[entryit]);     } } 

let's ignore std::move call now. can see, these 2 methods same thing, except when pushing new objects. better if have 1 method.

how can achieved? decltype useful? couldn't find way this.

the rationale behind needing old code calls method raw pointers , new code smart pointers, fast switch new mode not possible.

use std::pointer_traits<t>:

template <typename p, typename alloct, template <typename, typename> class containert> static void parse(containert<p, alloct> &entries, const rapidjson::value &jsondocument) {     (rapidjson::sizetype entryit = 0; entryit < jsondocument.size(); ++entryit)     {         entries.emplace_back(new typename std::pointer_traits<p>::element_type());         //                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^         entries[entryit]->parse(jsondocument[entryit]);     } } 

demo


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -