简体   繁体   中英

please help explain these code , maybe the 'None' in c++?

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM