是否存在用于编译时转换 a 成员类型的 Boost Hana 方法Struct类型名的 std::string 的 STL 容器的概念?
例如,
MyType t();
std::array<std::string, 3> ls = boost::hana::typesToString(t);
for(std::string x : ls){
std::cout << x << std::endl;
}
将“int string bool”输出到 STDOUT,
With
class MyType{
int x;
std::string y;
bool z;
}
该文档清楚地提供了获取实例的成员及其值的方法Struct概念,但我还没有找到任何可以做到这一点的东西成员类型。一个更简单的任务是:
int x;
std::string tName = boost::hana::typeId(x); //tName has value "int"
我读了这个帖子 https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c但我想知道 Hana 是否有一种开箱即用的干净方法。更好的是一种迭代成员的方法Struct无需知道他们的名字。
如果您使用 Clang,Hana 有一个实验性功能hana::experimental::type_name http://boostorg.github.io/hana/group__group-experimental.html#gaf14876d1f1a3c42ce7a0243d7b263bec。这可用于获取结构成员的类型名称:
#include <boost/hana.hpp>
#include <boost/hana/experimental/type_name.hpp>
namespace hana = boost::hana;
template <typename Struct>
auto member_type_names() {
constexpr auto accessors = hana::accessors<Struct>();
return hana::transform(
accessors,
hana::compose(
[](auto get) {
using member_type
= std::decay_t<decltype(get(std::declval<Struct>()))>;
return hana::experimental::type_name<member_type>();
},
hana::second
)
);
}
Demo (在 Wandbox 上直播 https://wandbox.org/permlink/uuhN0Ua9oYGvhmmy):
#include <iostream>
#include <string>
struct MyType {
int a;
std::string b;
float c;
};
BOOST_HANA_ADAPT_STRUCT(MyType, a, b, c);
int main() {
hana::for_each(member_type_names<MyType>(), [](auto name) {
// Note that the type of `name` is a hana::string, not a std::string
std::cout << name.c_str() << '\n';
});
}
Outputs:
int
std::__1::basic_string<char>
float
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)