【发布时间】:2020-04-18 07:59:26
【问题描述】:
我正在 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;
}
};
当然断言不起作用,这不是一个有效的启发式,因为这里 h(to) 是 100。我想让编译器在编译时检查 h(to) 等于 0。
【问题讨论】:
-
需求中不能有断言。抛开概念不谈,如果无法在编译时评估
h(to),您希望编译器如何验证h(to) == 100? (在您的示例中它不是一个常量表达式,因为operator()不是constexpr。) -
您使用的是哪个编译器?即使您删除了
assert,这个 (-> unsigned;) 也是无效的。正确的写法是使用-> std::same_as<unsigned>;或-> std::convertible_to<unsigned>;
标签: c++ c++20 heuristics concept