gpt4 book ai didi

c++ - 如何为启发式函数编写C++概念

转载 作者:行者123 更新时间:2023-12-01 14:52:55 32 4
gpt4 key购买 nike

我正在c++ 20中实现具有启发式功能的搜索算法。
我试图用类似这样的概念来约束我的算法可以使用的功能:

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;
}
};

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

最佳答案

I want to make the compiler check in compile time that h(to) equals 0.



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

当您开始怀疑值是否映射到正确的域中,或者函数是否将值映射到域中时,这不再是真正的“概念”。至少,从语言功能的 Angular 来看,这不是一个概念。

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

这也是为什么您应该对启发式使用命名成员函数的一个很好的理由,而不是假设具有 operator()重载(恰好从无符号整数映射到无符号整数)的任何事物都是“启发式”。

关于c++ - 如何为启发式函数编写C++概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282334/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com