Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::add_pointer vs classic pointer

Tags:

pointers

c++11

I just discovered the existence in C++ 11 of std::add_pointer. I had a look at the documentation at the following link but i do not really get the purpose of such an object:

http://www.cplusplus.com/reference/type_traits/add_pointer/

  • What is the main difference between for instance std::add_pointer<int> and a classic pointer ie int*?
  • How do you deference such a pointer? (do you use::value?)
  • what does add stand for?
like image 682
Stefano Avatar asked Apr 19 '16 11:04

Stefano


1 Answers

template<class T>struct tag_t{using type=T;};
template<class Tag>using type=typename Tag::Type;

template<template<class...>class Z, template<class...>class Test, class T>
struct apply_if:
  std::conditional_t< Test<T>{}, tag_t<Z<T>>, tag_t<T> >
{};
template<template<class...>class Z, template<class...>class Test, class T>
using apply_if_t = type<apply_if<Z,Test,T>>;

this takes a metafunction Z and a test Test and a type T, and returns Z<T> if the Test<T> is true, and otherwise returns T.

You cannot pass just put a * after the type to apply_if_t as Z. You can pass std::add_pointer or add_pointer_t.

Suppose you want to add pointers only if something is a function type (like int(int)). Then apply_if_t< std::add_pointer_t, std::is_function, X > will be X* if X is a function type, and X if not.

std::add_pointer<T>::type is to T* as int inc(int x){return x+1;} is to x+1.

like image 186
Yakk - Adam Nevraumont Avatar answered Oct 31 '22 14:10

Yakk - Adam Nevraumont