10

注意:以下所有内容都使用 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;

IE

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

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

也就是说,aDrawable是具有模板化 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>是否与概念匹配Drawable,这不太正确。(一个类型D要么具有所需的成员函数,要么没有:这不取决于Surface我们检查的具体内容。)

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

4

1 回答 1

7

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

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

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请注意,原型还有很大的改进空间。我有一个特定的 function void move_to(point2f ),但这个概念只要求它可以用 type 的左值调用point2f。没有要求move_to()两者line_to()都采用 type 的参数point2f,它们都可以采用完全不同的东西:

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

这种偏执狂造就了一个更好的原型,并用来说明这个问题可能有多么复杂。

于 2017-04-18T15:34:18.277 回答