Search code examples
c++boostc++14boost-interprocess

C++ Syntax: return statement with space after "template"; what does it mean


TL;DR:

What does the following Syntax for the functions return type and the return statement mean? (Code from boost::interprocess)

template <class T>
typename segment_manager::template construct_proxy<T>::type
  construct(char_ptr_holder_t name)
  {   return mp_header->template construct<T>(name);  }

Question

While trying to understand what is going on in these lines, i came across some akward syntax:

//Create a new segment with given name and size
boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only,
            "MySharedMemory", 65536);

//Initialize shared memory STL-compatible allocator
const ShmemAllocator allocator(segment.get_segment_manager());

ShmVector* v = segment.construct<ShmVector>("ShmVector")(allocator);

In the last line a function that "retruns 'throwing' construct proxy object" (boost documentation) is called. Apparently it allows us to call this construct proxy with the parameters that would be passed to the constructor of ShmVector(template parameter). Since I could not find the documentation for the construct proxy I decided to take a look and found the following code:

template <class T>
typename segment_manager::template construct_proxy<T>::type
  construct(char_ptr_holder_t name)
  {   return mp_header->template construct<T>(name);  }

And here my understanding stops:

  • It looks like there are two return types for the function construct, typename segment_manager::template and construct_proxy<T>::type, this does not make sense to me
  • template is used as a class member (segment_manager, mp_header), isn't such use of keywords dissallowed?
  • the functions seems to be actually returning two objects/parts: the syntax return partA partB; suggests so.

Solution

  • return mp_header->template construct<T>(name);
    

    The keyword template is used to indicate that construct is a member template of the type of *mp_header. You can imagine this as:

    return mp_header->construct<T>(name);
    

    which instantiates the construct member function with the type T, calls it with name as an argument, then returns the result. However, C++ requires the template keyword here since mp_header has dependent type. See: Where and why do I have to put the "template" and "typename" keywords?