这是 documentation of the Boost.Reflect library 的片段:
template<typename T>
struct xml_printer {
xml_printer( const T& c ):self(c){}
template<typename Type>
static xml_printer<Type> make( const Type& t ) {
return xml_printer<Type>(t);
}
template<typename Member, typename Class, Member Class::*p>
void operator()( const char* name )const {
std::cerr<<"<"<<name<<">"<<(self.*p)<<"</"<<name<<">\n";
}
const T& self;
};
我感到困惑的部分是访问者中 operator()
的声明:
template<typename Member, typename Class, Member Class::*p>
void operator()( const char* name )const
特别是Member Class::*p
部分。如果我理解正确的话,这个类型参数是为了让访问者能够解析成员而设置的,这是库以某种方式为成员存储的类型信息。然而,对我来说,两种类型相继编写看起来很不寻常。您能否向我解释一下这是如何工作的,或者提供一个使用此类声明调用函数的示例?
最佳答案
Member Class::*p
它是指向 Class
类型为 Member
的成员的指针。
所以,像这样的事情就会被认为是真的
auto printer = xml_printer<T>();
printer.template operator()<int, T, &T::x>("x");
其中 x
是 T
类型、int
类型的成员变量。
来自您链接的文档
#define BOOST_REFLECT_VISIT_MEMBER( r, visitor, elem ) \
visitor.template operator()
<BOOST_TYPEOF(type::elem),type,&type::elem>( BOOST_PP_STRINGIZE(elem) );
关于c++ - 这个 C++ 模板成员函数声明是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19447510/