需要约束模板成员函数的概念定义

Tri*_*dle 6 c++ templates c++-concepts

注意:以下所有内容都使用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...
    };
}
Run Code Online (Sandbox Code Playgroud)

现在我想定义另一个概念,Drawable它将任何类型与成员函数匹配:

template <typename S>
    requires Surface<S>()
void draw(S& surface) const;
Run Code Online (Sandbox Code Playgroud)

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

static_assert(Drawable<triangle>(), ""); // Should pass
Run Code Online (Sandbox Code Playgroud)

也就是说,a Drawable是具有模板化const成员函数draw()的东西,它对满足Surface要求的东西进行左值引用.这在单词中很容易指定,但我无法通过Concepts TS在C++中解决这个问题."明显"的语法不起作用:

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

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

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

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

static_assert(Drawable<triangle>(), "");
Run Code Online (Sandbox Code Playgroud)

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

现在我们只能检查特定的< Drawable,Surface> 是否与Drawable概念匹配,这是不对的.(类型D要么具有所需的成员函数,要么不具有:这不依赖于Surface我们检查的特定内容.)

我确信我可以做我正在做的事情,但我无法解决语法问题,但网上的例子还不多.有没有人知道如何编写一个概念定义,要求类型具有受约束的模板成员函数?

Bar*_*rry 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>());
}
Run Code Online (Sandbox Code Playgroud)

进而:

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

这些是有效的概念,可能有效。请注意,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 );
    // ...
};
Run Code Online (Sandbox Code Playgroud)

这种偏执产生了更好的原型,并有助于说明这个问题可能有多复杂。