C++ 语法:return 语句在 "template" 之后带有 space;这是什么意思

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

长话短说:

函数 return 类型和 return 语句的以下语法是什么意思? (代码来自 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);  }

问题

在试图理解 these lines 中发生的事情时,我遇到了一些笨拙的语法:

//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);

在最后一行 "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);  }

我的理解到此为止:

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

关键字template用来表示construct*mp_header类型的成员模板。您可以将其想象为:

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

实例化类型为 Tconstruct 成员函数,以 name 作为参数调用它,然后 returns 结果。但是,C++ 在这里需要 template 关键字,因为 mp_header 具有依赖类型。参见:Where and why do I have to put the "template" and "typename" keywords?