Kadir Erdem Demir Kadir Erdem Demir - 1 year ago 66
C++ Question

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

But there is one more catch smart_pointer can have many types like std::shared_ptr, boost::shared_ptr, std::weak_ptr so on.

So what I am trying finally is replace

typename SmartPointerType<DerivedClass>
with correct syntax :

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 )

return newList;

"Cast<>()" accepts any type of smart pointer that I am interested btw.

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.

I know I can use ".get()" but I am curious how can I make it work without ".get()".

Answer Source

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

    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).
  • Is accepted by your Cast() function.
  • Is usable in a boolean context.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download