簡體   English   中英

將容器的原始指針和智能指針傳遞給模板功能

[英]Pass container of raw pointers and smart pointers to template function

當容器(例如: std::vector )傳遞給函數模板時,是否有可能從容器中抽象出對象的指針類型?

我有以下兩種方法:

template <typename T, typename allocT, template <typename, typename> class containerT>
static void parse(containerT<T *, allocT> &entries, const rapidjson::Value &jsonDocument)
{
    for (rapidjson::SizeType entryIt = 0; entryIt < jsonDocument.Size(); ++entryIt)
    {
        entries.push_back(new T());
        entries[entryIt]->parse(jsonDocument[entryIt]);
    }
}

template <typename T, typename allocT, template <typename, typename> class containerT>
static void parse(containerT<std::unique_ptr<T>, allocT> &entries, const rapidjson::Value &jsonDocument)
{
    for (rapidjson::SizeType entryIt = 0; entryIt < jsonDocument.Size(); ++entryIt)
    {
        entries.push_back(std::move(std::unique_ptr<T>(new T())));            
        entries[entryIt]->parse(jsonDocument[entryIt]);
    }
}

我們暫時忽略std::move調用。 如您所見,除了推回新對象外,這兩種方法幾乎都做同樣的事情。 如果我只有一種方法會更好。

怎么能實現這一目標? decltype有用嗎? 我找不到辦法做到這一點。

需要這個的基本原理是舊代碼使用原始指針和帶有智能指針的新代碼調用方法,因此無法快速切換到新模式。

使用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)
{
    for (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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM