Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost: dereference a template argument if it's a pointer

Tags:

c++

templates

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.

like image 907
Alex B Avatar asked Jun 15 '11 07:06

Alex B


People also ask

Can you dereference a pointer?

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.

How do you dereference a pointer object?

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 .

Is pointer dereferencing expensive?

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.


1 Answers

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.

like image 159
Peter Alexander Avatar answered Nov 08 '22 08:11

Peter Alexander