注意:以下所有内容都使用 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
我们检查的具体内容。)
我确信有可能做我所追求的,但我无法弄清楚语法,而且网上还没有太多的例子。有人知道如何编写需要类型具有约束模板成员函数的概念定义吗?