简体   繁体   English

传递模板化智能指针类型作为模板参数

[英]Passing a templated smart pointer type as template parameter

I am trying to pass smart_pointer as a template parameter than use the type for dynamic casting etc.. 我正在尝试将smart_pointer作为模板参数传递,而不是将类型用于动态转换等。

But there is one more catch smart_pointer can have many types like std::shared_ptr, boost::shared_ptr, std::weak_ptr so on. 但是还有一个问题,smart_pointer可以具有很多类型,例如std :: shared_ptr,boost :: shared_ptr,std :: weak_ptr等。

So what I am trying finally is replace typename SmartPointerType<DerivedClass> with correct syntax : 所以我最后要尝试的是用正确的语法替换typename SmartPointerType<DerivedClass>

template < typename SmartPointerType<DerivedClass> >
std::vector<SmartPointerType<DerivedClass>> filterByType()
{
    std::vector<SmartPointerType<DerivedClass>> newList;
    for ( int i = 0; i < iTerrainList.size(); i++)
    {
        SmartPointerType<DerivedClass> castedTerrain = Cast<DerivedClass>(iTerrainList[i]);
        if ( castedTerrain )
            newList.push_back(castedTerrain);
    }

    return newList;
}

"Cast<>()" accepts any type of smart pointer that I am interested btw. “ Cast <>()”接受我感兴趣的任何类型的智能指针。

I find out I can use something like 我发现我可以使用类似

template <template <typename Type> class TemplateType>

But it didn't worked for with my c++03 compiler. 但这不适用于我的c ++ 03编译器。

I know I can use ".get()" but I am curious how can I make it work without ".get()". 我知道我可以使用“ .get()”,但我很好奇如何在没有“ .get()”的情况下工作。

Just let it work on any type: 只要让它适用于任何类型:

template <typename DerivedClassPtr>
std::vector<DerivedClassPtr> filterByType()
{
    std::vector<DerivedClassPtr> newList;
    for ( int i = 0; i < iTerrainList.size(); i++)
        if ( DerivedClassPtr terrain = Cast<typename DerivedClassPtr::element_type>(iTerrainList[i]) )
            newList.push_back(terrain);

    return newList;
}

Here, the requirements on the template type are that it: 在这里,对模板类型的要求是:

  • Can be stored in a vector (so must be copyable). 可以存储在向量中(因此必须是可复制的)。
  • Has element_type (so raw pointers won't work, for better or worse; you could fix this with type traits implemented yourself in C++03). 具有element_type (无论原始指针如何,无论好坏,您都无法使用;您可以使用在C ++ 03中实现的类型特征来解决此问题)。
  • Is accepted by your Cast() function. 被您的Cast()函数接受。
  • Is usable in a boolean context. 在布尔上下文中可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM