Reputation: 529
while reading the source code of folly (https://github.com/facebook/folly/blob/master/folly/Optional.h), I find a maybe "None" syntax implementation in c++ but cannot get the point. The codes as follow:
namespace detail { struct NoneHelper {}; }
typedef int detail::NoneHelper::*None;
const None none = nullptr;
what does these codes do? Is "None" a member function pointer ? plz help, thanks!
Upvotes: 1
Views: 5268
Reputation: 2074
None is a typedef of a pointer-to-member of an integer type.
Imagine you have a struct
namespace detail
{
struct NoneHelper
{
int a;
int b;
int c;
};
};
You would be able to say:
typedef int detail::NoneHelper* None;
const None memberA = &detail::NoneHelper::a;
This is a special syntax for acquiring pointer-to-member values. It can effectively be thought of as some sort of offset: struct NoneHelper has a member variable, of type integer, at this offset from its base pointer.
You would be able to use this syntax to modify that integer without having to explicitly state which integer member you want to modify; For example:
void setToFive(detail::NoneHelper& object, const None ptrToMember)
{
// .* is an operator that is used to dereference pointer-to-member variables
object.*ptrToMember = 5;
}
detail::NoneHelper obj;
obj.a = 1;
obj.b = 2;
obj.c = 3;
None ptrToA = &detail::NoneHelper::a; //Acquire the relative location of member a
None ptrToB = &detail::NoneHelper::b; //Acquire the relative location of member b
setToFive(obj, ptrToA); //Sets the value of "obj.a" to 5
setToFive(obj, ptrToB); //Sets the value of "obj.b" to 5
std::cout << obj.a << obj.b << obj.c; // should print out "553"
Edit: Please note, the "offset" idea only applies when it is a "pointer-to-member of an object". pointer-to-member syntax can be used for member functions as well ( int (SomeType::*)(int arg1)
), and (dear god hopefully) does not store an "offset" of where the member function might be contained within the object.
Upvotes: 1
Reputation: 180020
None is a null pointer. That's quite clear. But null pointers have types, too. NoneHelper
is a helper class which has no other function but to make the type of None
unique.
It's a pointer-to-member because that kind of pointer has limited conversions. In particular, you cannot accidentally cast a pointer-to-object to a pointer-to-member-function.
Upvotes: 5