Smart pointer type detection

I have a function that currently accepts two template parameters. One of them is expected to be a smart pointer, and the other is expected to be an object type. For example, SmartPtr<MyObject>as the first template parameter and MyObjectas the second template parameter.

template <typename T, typename TObject>

I would like to know if I can determine the second parameter MyObjectautomatically from the first parameter SmartPtr<MyObject>or not so that my template function is written as follows:

template <typename T>

And the type TObjectin the original template function is automatically determined from T, which is expected to be a smart pointer.

As requested, here is the function declaration and its use:

template <typename T, typename TObject>
T* CreateOrModifyDoc(T* doc, MyHashTable& table)
{
    T* ptr = NULL;

    if (!table.FindElement(doc->id, ptr))
    {
        table.AddElement(doc->id, new TObject());
        table.FindElement(doc->id, ptr);
    }       

    return ptr;
}
+3
source share
4

, , :

template<typename T>
void WhatIsIt(SmartPtr<T> ptr)
{ 
    printf("It is a: %s" typeid(T).name());
}
+11

, , typedef , :

template <typename T>
class SmartPtr
{
  public:
    typedef T element_type;

  // ...
};


template <typename PtrType, typename ObjType=PtrType::element_type>
void your_function_here(const PtrType& ptr)
{
  // ...
}
+3

Are you writing SmartPtr? If so add it to it

  typedef T element_type;
+2
source

All the smart pointers that I know about member support ::element_type. For example, boost shared_ptr: http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm#element_type , but smart pointers also stdsupport this convention.

template <typename T> class SharedPtr {
public:
    typedef T element_type;

    // ...
};
+1
source

All Articles