I have a function that currently takes in two template parameters. One is expected to be the smart pointer, and the other is expected to be the object type. For example, SmartPtr<MyObject>
as the first template parameter and MyObject
as the second template parameter.
template <typename T, typename TObject>
I would like to know whether I can determine the second parameter, MyObject
, automatically from the first parameter SmartPtr<MyObject>
or not so that my template function is written like this:
template <typename T>
And the type TObject
in 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;
}
If you know that the first template parameter will be the smart pointer type, why not declare your function with only one parameter and use it as such:
template<typename T>
void WhatIsIt(SmartPtr<T> ptr)
{
printf("It is a: %s" typeid(T).name());
}
If the classes that can serve as the first template parameter can be made to provide a handy typedef by a common name, you can do this:
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)
{
// ...
}
Did you write SmartPtr? If so, add this to it
typedef T element_type;
All smart pointers I know of support the member ::element_type
. For example boost's shared_ptr: http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm#element_type , but also the std
smart pointers support this convention.
template <typename T> class SharedPtr {
public:
typedef T element_type;
// ...
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.