Domanda

I have a template function that is enabled (through a std::enable_if) its parameter is a raw pointer, or has a std::iterator category or is a std::nullptr_t. In that function, a raw pointer (a data member) is set equal to the parameter, like that :

template<class T> void myFunction(T it) 
{
    _ptr = &*it;
}

The &* works well for pointer and iterator ... but it fails for a std::nullptr_t. Is there any solution available to avoid to write 2 different functions ?

Thank you.

È stato utile?

Soluzione

The simplest thing is to change the function to have two overloads, one for raw pointers/nullptr_t that just stores the value and one selected by SFINAE for iterators with your current implementation, although you should note that this will fail under some circumstances (in particular if iterator::value_type overloads unary operator&).

Altri suggerimenti

As always, we can solve this with a trait. This time, let's not write a full class, since a simple function overload suffices.

#include <cstddef>
#include <memory>

template <typename T>
T get_addr(T t) { return std::addressof(*t); } // #1

std::nullptr_t get_addr(std::nullptr_t np) { return np; }

Usage:

T _ptr = get_addr(it);

(This trait also works if the type pointed to by T overloads operator&.)

You're invited to guard the overload #1 with the same enable_if condition that you have in your main template.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top