在boost::spirit::x3中用作标记的奇怪构造

Strange construct that used as tag in boost::spirit::x3

本文关键字:spirit boost x3      更新时间:2023-10-16

以下上下文中奇怪的语言结构X< class Y > Y;是什么?

#include <iostream>
#include <sstream>
#include <typeinfo>
#include <type_traits>
#include <cstdlib>
#include <cxxabi.h>
template< typename T >
std::string const type_info_str()
{
    int status = 0;
    auto realname_(abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status));
    switch (status) {
    case -1: return "Could not allocate memory";
    case -2: return "Invalid name under the C++ ABI mangling rules";
    case -3: return "Invalid argument to demangle";
    }
    std::ostringstream oss;
    if (std::is_volatile< T >::value) {
        oss << "volatile ";
    }
    oss << realname_;
    std::free(realname_);
    if (std::is_const< T >::value) {
        oss << " const";
    }
    if (std::is_rvalue_reference< T >::value) {
        oss << " &&";
    } else if (std::is_lvalue_reference< T >::value) {
        oss << " &";
    }
    return oss.str();
}
template< typename T >
struct X { };
int main()
{
    X< class Y > Y;
    std::cout << type_info_str< decltype(Y) >() << std::endl; // X<main::Y>
    return EXIT_SUCCESS;
}

它的目的和语义是什么?

让我们来分解一下:

X  <class Y> Y 
|  ^^^^^^^^^ |
|      |     |
|      |     |
|      |     ---> name of the variable 
|      |
|      ---> the struct is a template which is instantiated with a type 
|          (in this case, the type is an incomplete class named Y)
|
---> struct declared globally

正如Agent_L所提到的,类名和变量之间没有冲突,因为可以从上下文中推断出真正的含义:类型或变量