为什么 boost::hana 的集合不是默认可构造的?

Why is boost::hana's set not default constructable?

本文关键字:默认 boost hana 集合 为什么      更新时间:2023-10-16

今天我发现boost::hanamapset不是默认可构造的,而tuple是。这有什么特别的原因吗,因为它很烦人。

这个

#include <boost/hana/set.hpp> 
//                   ^^^ or map
constexpr boost::hana::set<> a{};
//                     ^^^ or map
int main(){}

失败,并出现以下错误:

main.cpp:3:30: error: no matching constructor for initialization of 'const boost::hana::set<>'
constexpr boost::hana::set<> a{};
                             ^~~
/home/russellg/Documents/boost/hana-0.6.0/include/boost/hana/set.hpp:65:28: note: candidate constructor not viable: requires single argument 'xs', but no arguments were provided
        explicit constexpr set(tuple<Xs...> const& xs)
                           ^
/home/russellg/Documents/boost/hana-0.6.0/include/boost/hana/set.hpp:69:28: note: candidate constructor not viable: requires single argument 'xs', but no arguments were provided
        explicit constexpr set(tuple<Xs...>&& xs)
                           ^
/home/russellg/Documents/boost/hana-0.6.0/include/boost/hana/set.hpp:57:12: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were
      provided
    struct set
           ^
/home/russellg/Documents/boost/hana-0.6.0/include/boost/hana/set.hpp:57:12: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were
      provided
1 error generated.

即使有一个空的地图或集合是完全有效的:

#include <boost/hana/set.hpp>
//                   ^^^ or map
constexpr auto a = boost::hana::make_set();
//                                   ^^^ or map
int main(){}

它完美地编译。

感谢您的帮助。

编辑:

实际上,它是否为空并不重要,默认构造map s和set s总是非法的。

hana::sethana::map表示是实现定义的。文档警告不要直接使用它们,并提到创建它们的规范方法分别是通过hana::make_sethana::make_map。文件说明:

hana::set的实际表示是由实现定义的。特别是,不应想当然地认为模板参数的顺序和任何构造函数或赋值运算符的存在。创建hana::set的规范方式是通过hana::make_set

hana::tuple是一个更简单的容器,记录它的表示,并努力保持与std::tuple的一些奇偶性。hana::basic_tuple文档说明:

〔…〕hana::tuple旨在提供一个与std::tuple〔…〕有点接近的接口


至于为什么hana::sethana::map的表示是实现定义的,请考虑阅读常见问题解答,但简而言之:

  • 允许更灵活地实现编译时和运行时优化
  • 知道类型通常不是很有用

有一个github问题需要考虑为hana::map添加一个默认构造函数。