C++ 概念和提升几何图形

C++ concepts and boost geometry

提问人:Acave At 提问时间:11/14/2023 更新时间:11/14/2023 访问量:43

问:

我有一个运算符模板,它调用类型 的 boost 几何函数模板 , .如果无法为类型实例化此函数模板,则我希望编译器选择回退运算符模板。如何使用 c++20 概念进行管理?T1T2T1T2

以下内容不编译:

#include <iostream>
#include <concepts>
#include <boost/geometry.hpp>

/*
 * Concept requiring that the template function "boost::geometry::within<T1, T2>"
 * can be instantiated for types T1, T2
 */
template<typename T1, typename T2>
concept WithinCanBeInstantiated = requires(const T1& t1, const T2& t2)
{
  boost::geometry::within<T1, T2>(t1, t2);
};

struct Within {
    /*
     * Operator template that should be used, if "boost::geometry::within<T1, T2>"
     * can be instantiated for types T1, T2
     */
    template <typename T1, typename T2>
    requires WithinCanBeInstantiated<T1, T2>
    bool operator()(const T1& t1, const T2& t2) const
    {
      return boost::geometry::within<T1, T2>(t1, t2);
    }
    
    /*
     * Operator template that should be used, if "boost::geometry::within<T1, T2>"
     * cannot be instantiated for types T1, T2
     */
    template <typename T1, typename T2>
    requires (not WithinCanBeInstantiated<T1, T2>)
    bool operator()(const T1& t1, const T2& t2) const
    {
      return false;
    }

};

int main() {
    typedef boost::geometry::model::d2::point_xy<double> point_type;
    typedef boost::geometry::model::polygon<point_type> polygon_type;

    polygon_type poly;
    boost::geometry::read_wkt(
        "POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)"
            "(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))", poly);

    point_type p(4, 1);

    Within within;
    std::cout << "within exists: " << within(p, poly) << " no within: " << within(poly, p);
}

尝试编译

g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

我做错了什么? 提前非常感谢!

模板 C++-概念 boost-geometry

评论

0赞 n. m. could be an AI 11/14/2023
您不能拦截static_assert或任何其他硬错误并将其变成一个很好的替换失败。
0赞 Acave At 11/14/2023
@n.m.couldbeanAI 问题是,我不知道static_assert或其他硬错误与替换失败之间的区别。最后,编译器拒绝实例化 boost::geometry::within<T1、T2>,我期待,这正是概念要求检查的内容.....
0赞 n. m. could be an AI 11/14/2023
“我不知道static_assert或其他硬错误与替换失败之间的区别。”如果不很好地理解这种区别,你就无法有效地使用概念。粗略地说,替换失败发生在参数替换时,并本地化在模板头中。硬错误发生在模板实例化时,并本地化在模板正文中。
0赞 Acave At 11/14/2023
@n.m.couldbeanAI 好的,谢谢你的解释。c++概念对我来说是一个新概念,而且我也没有参加过大学的编译器讲座,所以如果有人能告诉我,如果这样,我想要实现的目标,是否可以通过 c++ 概念(以及如何实现)来,那将是有很大帮助的。
0赞 n. m. could be an AI 11/14/2023
他们通常不会在大学里教这些东西。它非常特定于 C++ 和 C++>=20。不,你无法实现你想要的。概念要求不是根据哪些模板可以实例化或不能实例化来指定,而是根据哪些模板可以或不能找到来指定。例如,如果您有一个并且您正在尝试使用 ,则找不到合适的模板。这是替换失败。您不能将两者的类型替换为相同的 .的正文是无关紧要的。template <typename T> T min(T, T)min(42, "bye")42"bye"Tmin

答: 暂无答案