我正在使用 boost::hana 反射(reflect)结构,我正在尝试获取成员的名称。我的工作解决方案使用特定于 gcc 的宏,我想用更通用的东西替换它。
提供反射的标题看起来有点像这样
#include <boost/hana.hpp>
#include <string>
#include <iostream>
struct ReflectedStruct
{
virtual void PrintMemberTypes() = 0;
virtual ~ReflectedStruct(){}
};
template<class T> struct meta {
static const std::string& get_name() {return T::class_name;}
};
#define TYPE_NAME(type) \
template<>struct meta<type> { \
static constexpr const char* class_name = #type; \
static const char* get_name() {return class_name;} \
};
TYPE_NAME(double);
#define REFLECT_STRUCT(structure_name, ...) \
struct structure_name : ReflectedStruct { \
BOOST_HANA_DEFINE_STRUCT(structure_name, __VA_ARGS__ ); \
void PrintMemberTypes() { \
boost::hana::for_each(boost::hana::accessors<structure_name>(), \
[&](auto pair) { \
std::cout \
<< meta< typeof( boost::hana::second(pair)(*this) ) >::get_name() \
<< std::endl; \
} \
); \
} \
}; \
TYPE_NAME(structure_name);
使用它看起来像这样:
REFLECT_STRUCT(Runway,
(double, lat),
(double, lon),
(double, hdg),
(double, alt)
);
int main()
{
Runway r;
r.PrintMemberTypes(); // prints "double, double, double, double"
return 0;
}
我的问题是看起来像这样的行:
meta< typeof( boost::hana::second(pair)(*this) ) >::get_name()
更具体地说,问题是 typeof()
这是特定于 gcc 的。以下是我尝试过的一些方法:
// Ok, but gcc-specific. Resolves to "double"
typeof ( boost::hana::second(pair)(*this) )
// Error, is type "double&", I haven't specialized meta<> for that.
decltype ( boost::hana::second(pair)(*this) )
// error: Doesn't seem to resolve to a type
std::remove_reference<decltype( boost::hana::second(pair)(*this) )>::type
// error: Doesn't seem to resolve to a type
boost::hana::typeid_(boost::hana::second(pair)(*this))::type
我需要没有引用的类型。
我想另一个选择是专门化 meta<>
用于引用而不是类型本身。
最佳答案
// error: Doesn't seem to resolve to a type
std::remove_reference<decltype( boost::hana::second(pair)(*this) )>::type
由于 pair
的类型基本上是一个模板参数,type
是一个从属名称,因此您需要使用 typename
:
typename std::remove_reference<decltype( boost::hana::second(pair)(*this) )>::type
// error: Doesn't seem to resolve to a type
boost::hana::typeid_(boost::hana::second(pair)(*this))::type
您需要记住 typeid_
返回一个值,而不是类型,因此您不能直接在其结果上使用 ::type
。您需要使用 decltype
:
typename decltype(boost::hana::typeid_(boost::hana::second(pair)(*this)))::type
关于c++ - Boost hana 获取字符串中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607613/