What can I use to dereference a template argument if it's a pointer (or a smart pointer), or leave it as is if it's not?
template<class T> void subf(const T& item)
{
item.foo();
}
template<class T> void f(const T& item)
{
subf(magic_dereference_function(item));
}
Anything in Boost is an option.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
The . * operator is used to dereference pointers to class members. The first operand must be of class type. If the type of the first operand is class type T , or is a class that has been derived from class type T , the second operand must be a pointer to a member of a class type T .
The dereferencing of a pointer shouldn't be much more than copying an address to a (address)register. Thats all. Dereferencing usually means reading from that address as well. Which may vary in cost depending on cache, locality and such.
template <typename T>
T& maybe_deref(T& x) { return x; }
template <typename T>
T& maybe_deref(T* x) { return *x; }
You'll have to add overloads for smart pointers individually. There's no way to detected if a class is a "smart pointer". You could detect the presence of operator->
, but that doesn't mean it's a smart pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With