C++ 使用Boost.Hana定义编译时可比较对象

C++ 使用Boost.Hana定义编译时可比较对象,c++,metaprogramming,c++14,boost-hana,C++,Metaprogramming,C++14,Boost Hana,我正在努力将用户定义的类型作为hana::map中的键。 我遇到一个静态断言,说必须在 编译时。我确实为组合实现了constexpr bool操作符== (我相信)所有的。有什么问题吗?因为我的操作符==是constepr,所以我的对象在编译时应该是可比较的,对吗?您必须从比较操作符返回一个积分常量,而不是constepr bool。以下工作: #include <boost/hana.hpp> #include <cassert> #include <string

我正在努力将用户定义的类型作为
hana::map
中的键。 我遇到一个
静态断言
,说必须在 编译时。我确实为组合实现了
constexpr bool操作符==

(我相信)所有的。有什么问题吗?因为我的
操作符==
constepr
,所以我的对象在编译时应该是可比较的,对吗?

您必须从比较操作符返回一个
积分常量,而不是
constepr bool
。以下工作:

#include <boost/hana.hpp>
#include <cassert>
#include <string>
namespace hana = boost::hana;

template <int i>
struct UserDefined { };

template <int a, int b>
constexpr auto operator==(UserDefined<a>, UserDefined<b>) 
{ return hana::bool_c<a == b>; }

template <int a, int b>
constexpr auto operator!=(UserDefined<a>, UserDefined<b>) 
{ return hana::bool_c<a != b>; }

int main() {
    auto m = hana::make_map(
        hana::make_pair(UserDefined<0>{}, std::string{"zero"}),
        hana::make_pair(UserDefined<1>{}, 1)
    );

    assert(m[UserDefined<0>{}] == "zero");
    assert(m[UserDefined<1>{}] == 1);
}
操作符[]
中,返回值的类型取决于键。我们必须以某种方式提取一个
bool
,表示与该键关联的值,但该
bool
必须在编译时已知(即,是一个常量表达式),以使返回类型依赖于它。因此在
操作符[]
中,我们需要一个
constexpr bool
表示
key
是否是与map的给定值相关联的键。但是,由于无法指定
key
constepr
参数这一事实,因此我们无法从该参数中提取
constepr bool
,即使
key
定义了
constepr bool操作符==
。换句话说,

template <typename Key>
auto operator[](Key const& key) {
    // impossible whatever some_other_key_of_the_map is
    constexpr bool found = (key == some_other_key_of_the_map);

    // return something whose type depends on whether the key was found
}
模板
自动操作员[](键常量和键){
//不管地图上的某个键是什么,都是不可能的
constexpr bool found=(key==映射的某个或另一个key);
//返回其类型取决于是否找到密钥的内容
}
实现上述目标的唯一方法是执行以下操作

template <typename Key>
auto operator[](Key const& key) {
    constexpr bool found = decltype(key == some_other_key_of_the_map)::value;

    // return something whose type depends on whether the key was found
}
模板
自动操作员[](键常量和键){
constexpr bool found=decltype(key==some\u other\u key\u的映射)::value;
//返回其类型取决于是否找到密钥的内容
}
因此要求
Key::operator==
返回一个
integrationconstant
。这里有更多关于这个和相关概念的信息

template <typename Key>
auto operator[](Key const& key) {
    constexpr bool found = decltype(key == some_other_key_of_the_map)::value;

    // return something whose type depends on whether the key was found
}