Is there a standard library function opposite the address?

I have an algorithm where I convert from pointers to class

std::vector<MyClass>  input;
std::vector<MyClass*> ptrs;
std::vector<MyClass>  output;

So, to get ptrs, I do

transform(input.begin(), input.end(), back_inserter(ptrs), addressof<MyClass>);

Is there an opposite operation in the standard library , for example deref_of, so that I can get the result as:

transform(ptrs.begin(), ptrs.end(), back_inserter(output), deref_of<MyClass*>);
+4
source share
2 answers

You can do this using boost::indirect_iterator.

std::copy(boost::make_indirect_iterator(ptrs.begin()),
          boost::make_indirect_iterator(ptrs.end()),
          std::back_inserter(output));

Live demo

+6
source

There are no such things in the standard library.

However, you can write this yourself:

template<typename T>
T& deref(T * ptr) { return *ptr; }                //non-const version

template<typename T>
T const & cderef(T const * ptr) { return *ptr; }  //const version   

You should use it as deref<MyClass>, rather than deref<MyClass*>.


In C ++ 14, you can use a common lambda simply:

auto deref = [](auto * ptr) { return *ptr; };

deref deref<MyClass> ( ). , . , ++ 11 ( ++ 03) :

static const struct deref_t  //static const applies to the object
{
    template<typename T>
    T& operator()(T const * ptr) const { return *ptr; }

}deref;  //declare an object as well.

deref. .

, .

+6

Source: https://habr.com/ru/post/1540474/


All Articles