繁体   English   中英

如何为启发式 function 编写 c++ 概念

[英]How to write a c++ concept for Heuristic function

我正在用 c++ 20 中的启发式 function 实现搜索算法。我试图约束 function 我的算法可以使用如下概念:

template<typename SelfType, unsigned from, unsigned to>
concept Heuristic = requires(SelfType h, unsigned current)
{
    { h(current) } -> unsigned;

    assert(h(to) == 0);
};

然后我可以写如下内容:

template<unsigned from, unsigned to>
struct H
{
    unsigned operator()(unsigned current)
    {
        return to - current + 100;
    }
};

当然,断言不起作用,这不是有效的启发式方法,因为这里 h(to) 是 100。我想让编译器在编译时检查 h(to) 等于 0。

我想让编译器检查 h(to) 等于 0 的编译时间。

这只有在编译器能够在编译时调用h(to)时才有可能。 它不能,因为不能保证调用的任何 function 都是constexpr SelfType可以是 function 指针类型,并且 function 指针不携带constexpr 概念甚至无法检查某物是否为常量表达式。

当您开始考虑值 map 是否进入正确的域,或者 function 是否将值映射到域时,这不再是一个真正的“概念”。 或者至少,它不是语言特征意义上的概念。

也就是说,当我们认为某些东西是语言无法验证的概念的特定用户的要求时。 C++20 概念库充满了这些公理化的概念要求。

这也是为什么您应该使用命名成员 function 作为启发式方法的一个很好的理由,而不是假设任何具有operator()重载的东西都会发生在从无符号整数到无符号整数的 map 是“启发式”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM