该文档的hana::keys
说,我可以用它在函数调用语法如hana::keys(s)
这里s
是满足概念的类的实例hana::Struct
,并返回键对象序列。
一个相关的函数hana::accessors
返回一个访问器函数序列,该函数可用于从该结构的实例中获取相应的成员。
hana::accessors
可以以两种方式使用:
hana::accessors(s)
hana::accessors<S>()
都是合法的,constexpr
当S = decltype(s)
-对应于structure的序列时,函数返回相同的东西S
。
当我尝试使用语法时hana::keys
,出现错误。这是一个MCVE,改编自hana
文档中的示例:
#include <boost/hana.hpp>
#include <boost/hana/define_struct.hpp>
#include <boost/hana/keys.hpp>
#include <iostream>
#include <string>
namespace hana = boost::hana;
struct Person {
BOOST_HANA_DEFINE_STRUCT(Person,
(std::string, name),
(unsigned short, age)
);
};
// Debug print a single structure
template <typename T>
void debug_print_field(const char * name, const T & value) {
std::cout << "\t" << name << ": " << value << std::endl;
}
template <typename S>
void debug_print(const S & s) {
std::cout << "{\n";
hana::for_each(hana::keys<S>(), [&s] (auto key) {
debug_print_field(hana::to<char const *>(key), hana::at_key(s, key));
});
std::cout << "}" << std::endl;
}
// Debug print compare two structures
int main() {
Person john{"John", 30}, kevin{"Kevin", 20};
debug_print(john);
std::cout << std::endl;
debug_print(kevin);
std::cout << std::endl;
}
$ g++-6 -std=c++14 -I/home/chris/boost/boost_1_61_0/ main.cpp
main.cpp: In function ‘void debug_print(const S&)’:
main.cpp:28:30: error: expected primary-expression before ‘>’ token
hana::for_each(hana::keys<S>(), [&s] (auto key) {
^
main.cpp:28:32: error: expected primary-expression before ‘)’ token
hana::for_each(hana::keys<S>(), [&s] (auto key) {
^
我使用时效果很好hana::keys(s)
。
但是在我的实际应用程序中,我没有该结构的实例,它只是一个模板参数。
作为一个hack,我做到了:
// Work around for `hana::keys`
template <typename S>
constexpr decltype(auto) get_hana_keys() {
return decltype(hana::keys(std::declval<S>())){};
}
我认为这是基于我hana
对文档中描述的实现细节的有限理解而实现的。-hana::keys
应该返回一个编译时字符串序列,并且所有信息都包含在类型中,因此仅获取类型和默认构造应该等效。
当我get_hana_keys<S>()
在我的MCVE中使用它时,它将编译并运行良好。
但是我不知道它是否真的正确,或者我所做的假设是否超出了文档所允许的范围。
我正在使用boost版本1.61
和gcc 6.2.0
。
我想知道的是,
是否有充分的理由hana::keys<S>()
不起作用,或者仅仅是一个疏忽?hana
似乎设计得非常细致,所以我倾向于在这里进行第二次猜测。
我创建的hack或改进它的方法有什么问题吗?
好问题!
是否有充分的理由
hana::keys<S>()
不起作用,或者仅仅是一个疏忽?
之所以hana::keys<S>()
不起作用,是因为在一般情况下无法实现它。确实,keys
最初是针对进行设计的hana::map
,其中的键可以是有状态的,因此您确实需要一个对象来返回有意义的东西。对象不是检索a的键所必需的事实hana::Struct
只是一个巧合。
我创建的hack或改进它的方法有什么问题吗?
从技术上讲,hana::string
没有记录为默认可构造的,因此hana::tuple
不能保证其中的默认构造有效。但是,这是我已经在1eebdb中修复的疏忽,所以您很好。
话虽这么说,也许是以下惯用的解决方案:
template <typename S>
constexpr auto get_hana_keys() {
return hana::transform(hana::accessors<S>(), hana::first);
}
事实上,这就是我们定义hana::keys
为hana::Struct
秒。
最后,请注意,与hana::Struct
语言相关的反射将更好地服务于与之相关的所有内容,因此请原谅Hana提供的对反射的古怪支持。没有语言支持,在这方面做任何事情都很难。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句