简体   繁体   English

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

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

I am implementing a search algorithm with heuristic function in c++ 20. I'm trying to constrain the function my algorithm can use with a concept like so:我正在用 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);
};

Then I can write something like:然后我可以写如下内容:

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

Of course the assert does not work and that is not a valid heuristic because here h(to) is 100. I want to make the compiler check in compile time that h(to) equals 0.当然,断言不起作用,这不是有效的启发式方法,因为这里 h(to) 是 100。我想让编译器在编译时检查 h(to) 等于 0。

I want to make the compiler check in compile time that h(to) equals 0.我想让编译器检查 h(to) 等于 0 的编译时间。

That would only be possible if the compiler was able to call h(to) at compile time.这只有在编译器能够在编译时调用h(to)时才有可能。 Which it can't, because there's no guarantee that whatever function gets invoked is constexpr .它不能,因为不能保证调用的任何 function 都是constexpr SelfType could be a function pointer type, and function pointers don't carry around constexpr . SelfType可以是 function 指针类型,并且 function 指针不携带constexpr And concepts can't even check whether something is a constant expression or not.概念甚至无法检查某物是否为常量表达式。

When you start getting into questions of whether values map into the proper domain, or whether a function maps values into a domain, that isn't really a "concept" anymore.当您开始考虑值 map 是否进入正确的域,或者 function 是否将值映射到域时,这不再是一个真正的“概念”。 Or at least, it isn't a concept in the sense of the language feature.或者至少,它不是语言特征意义上的概念。

That is, there are certain things when we consider to be requirements of a particular user of a concept which the language cannot verify.也就是说,当我们认为某些东西是语言无法验证的概念的特定用户的要求时。 The C++20 concept library is full of these axiomatic concept requirements. C++20 概念库充满了这些公理化的概念要求。

This is also a good reason why you should use a named member function for your heuristics, rather than assuming that anything which has an operator() overload that just so happens to map from unsigned integers to unsigned integers is a "heuristic".这也是为什么您应该使用命名成员 function 作为启发式方法的一个很好的理由,而不是假设任何具有operator()重载的东西都会发生在从无符号整数到无符号整数的 map 是“启发式”。

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

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