问题描述
是否存在一种Boost Hana方法,用于在编译时将 Struct 概念的成员类型转换为类型名称为std :: string的STL容器?
Does there exist a Boost Hana method for compile-time converting the types of members of a Struct concept to a STL container of std::string's of the typenames?
例如,
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,
Yields "int string bool" to STDOUT,
使用
class MyType{
int x;
std::string y;
bool z;
}
文档清楚地提供了用于获取 Struct 概念的实例的成员及其值的方法,但是我还没有找到针对成员的类型进行此操作的任何方法.一个简单的任务是:
The documentation clearly provides methods for getting the members and their values of an instance of a Struct concept, but I haven't found anything there that does this for the types of the members. A simpler task would be to do:
int x;
std::string tName = boost::hana::typeId(x); //tName has value "int"
我已阅读这篇文章,但我想知道Hana中是否有开箱即用的干净方法.甚至更好的方法是遍历 Struct 的成员而不必按名称知道它们的方式.
I've read this post but I'd like to know if there's a clean way out-of-the-box in Hana. Even better would be a way to iterate through the members of the Struct without having to know them by name.
推荐答案
如果您使用的是Clang,Hana具有实验功能 hana::experimental::type_name
.这可以用来获取结构成员的类型名称:
If you are using Clang, Hana has an experimental feature hana::experimental::type_name
. This can be used to get the type-names of the members of the struct:
#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
)
);
}
演示(生活在魔盒中):
#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';
});
}
输出:
int
std::__1::basic_string<char>
float
这篇关于Boost Hana:将Hana类型转换为std :: string的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!