gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:58 25 4
gpt4 key购买 nike

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

error: 'auto' parameter not permitted in this context

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

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

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

template argument deduction/substitution failed: couldn't deduce template parameter 'S'

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

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

最佳答案

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

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

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 原型(prototype)还有很大的改进空间。我有一个特定的函数 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 );
// ...
};

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

关于c++ - 需要约束模板成员函数的概念定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37655113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com