【问题标题】:Concept definition requiring a constrained template member function需要约束模板成员函数的概念定义
【发布时间】:2016-10-05 22:11:24
【问题描述】:

注意:以下所有内容都使用 GCC 6.1 中的 Concepts TS 实现

假设我有一个概念Surface,如下所示:

template <typename T>
concept bool Surface() {
    return requires(T& t, point2f p, float radius) {
        { t.move_to(p) };
        { t.line_to(p) };
        { t.arc(p, radius) };
        // etc...
    };
}

现在我想定义另一个概念,Drawable,它可以匹配任何具有成员函数的类型:

template <typename S>
    requires Surface<S>()
void draw(S& surface) const;

struct triangle {
    void draw(Surface& surface) const;
};

static_assert(Drawable<triangle>(), ""); // Should pass

也就是说,Drawable 是具有模板化 const 成员函数 draw() 的东西,它对满足 Surface 要求的东西进行左值引用。这很容易用文字来指定,但我不太清楚如何使用 Concepts TS 在 C++ 中做到这一点。 “显而易见”的语法不起作用:

template <typename T>
concept bool Drawable() {
    return requires(const T& t, Surface& surface) {
        { t.draw(surface) } -> void;
    };
}

错误:此上下文中不允许使用“auto”参数

添加第二个模板参数允许编译概念定义,但是:

template <typename T, Surface S>
concept bool Drawable() {
    return requires(const T& t, S& s) {
        { t.draw(s) };
    };
}

static_assert(Drawable<triangle>(), "");

模板参数推导/替换失败: 无法推导出模板参数'S'

现在我们只能检查特定的 Drawable, Surface> pair 是否与 Drawable 概念匹配,这不太正确。 (D 类型要么具有所需的成员函数,要么没有:这不取决于我们检查哪个特定的 Surface。)

我确信可以做我想做的事,但我无法弄清楚语法,而且网上还没有太多示例。有人知道如何编写需要类型具有约束模板成员函数的概念定义吗?

【问题讨论】:

  • 您是否尝试过在概念定义中使用 std::is_member_function_pointer ?可能会奏效。因为我没有在工作中安装 gcc,所以无法在这里查看...

标签: c++ templates c++-concepts


【解决方案1】:

您正在寻找一种编译器合成Surface原型 的方法。也就是说,某种私有的、匿名的类型,最低限度地满足Surface 概念。尽可能少。 Concepts TS 目前不允许自动合成原型的机制,因此我们只能手动进行。这是一个相当不错的complicated process,因为很容易想出具有概念指定的更多功能的原型候选。

在这种情况下,我们可以想出类似的方法:

namespace archetypes {
    // don't use this in real code!
    struct SurfaceModel {
        // none of the special members
        SurfaceModel() = delete;
        SurfaceModel(SurfaceModel const& ) = delete;
        SurfaceModel(SurfaceModel&& ) = delete;
        ~SurfaceModel() = delete;
        void operator=(SurfaceModel const& ) = delete;
        void operator=(SurfaceModel&& ) = delete;

        // here's the actual concept
        void move_to(point2f );
        void line_to(point2f );
        void arc(point2f, float);
        // etc.
    };

    static_assert(Surface<SurfaceModel>());
}

然后:

template <typename T>
concept bool Drawable() {
    return requires(const T& t, archetypes::SurfaceModel& surface) {
        { t.draw(surface) } -> void;
    };
}

这些是有效的概念,可能有效。请注意,SurfaceModel 原型还有很大的改进空间。我有一个特定的函数void move_to(point2f ),但这个概念只要求它可以用point2f 类型的左值调用。没有要求move_to()line_to() 都接受point2f 类型的参数,它们都可以接受完全不同的东西:

struct SurfaceModel {    
    // ... 
    struct X { X(point2f ); };
    struct Y { Y(point2f ); };
    void move_to(X );
    void line_to(Y );
    // ...
};

这种偏执会形成一个更好的原型,并用来说明这个问题可能有多复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2013-03-18
    • 2020-08-10
    相关资源
    最近更新 更多