gpt4 book ai didi

C++ 概念 : Some signatures function conversion

转载 作者:行者123 更新时间:2023-11-28 01:56:50 25 4
gpt4 key购买 nike

不幸的是,我找到的唯一教程是关于 concepts是概念精简版教程(它真的很基础)。即使有技术规范,也有一些我不知道如何转化为概念的签名函数(可能只是因为我的英语不好,我不能很好地阅读技术规范)。

所以有一个签名函数列表我仍然不知道如何“翻译”:

CFoo --> 类 CFoo {};

  • void Foo1() const;
  • CFoo& Foo2();
  • void Foo3(CFoo&);
  • {static, friend, ... } void Foo4();
  • template < typename ... Args >
    void Foo5(Args && ... args);

我想为具有这些功能的类提供某种接口(interface)。甚至不知道在这一点上是否有可能。 Foo2 和 Foo3 似乎是同一个问题。


老实说,我真的很想知道 Foo2 和 Foo5。

我为 Foo2 尝试了一些东西,但我对 Foo5 没有任何想法:

class Handle {};

template < typename Object >
concept bool C_Object =
requires(Handle handle) {
{get(handle)} -> Object&
};

template < C_Object Object >
class Foo {

Object obj;
};

int main() {

Foo<int> test;
return 0;
}

我知道这不会编译,因为 Foo 没有 get menber,但这些不是正确的错误:

Test1.cpp:6:16: error: there are no arguments to ‘get’ that depend on a template parameter, so a declaration of ‘get’ must be available [-fpermissive]
{get(handle)} -> Object&
^
Test1.cpp:6:16: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
Test1.cpp: In function ‘int main()’:
Test1.cpp:18:10: error: template constraint failure
Foo<int> test;
^
Test1.cpp:18:10: note: constraints not satisfied
Test1.cpp:4:14: note: within ‘template<class Object> concept const bool C_Object<Object> [with Object = int]’
concept bool C_Object =
^~~~~~~~
Test1.cpp:4:14: note: with ‘Handle handle’
Test1.cpp:4:14: note: the required expression ‘get(handle)’ would be ill-formed

如果有人可以指出一些资源或者解决方案,为什么不呢?会很棒的。

祝你今天愉快

最佳答案

I know this won't compile because Foo don't have a get menber […]

概念处理普通表达式。特别是 requires 的范围表达式是正常范围,而不是类范围。这个概念可能更明显:

template<typename Lhs, typename Rhs>
concept bool Addable = requires(Lhs lhs, Rhs rhs) {
lhs + rhs;
};

Addable<int, long>已满足,因为给定 int lhs; long rhs;然后 lhs + rhs是一个有效的表达式。我们在参数列表中明确引入的两个(假装)变量上使用内置加法运算符,而不是调用成员 operator+在隐式 *this 上.

概念是关于更广泛意义上的接口(interface)(如“API”),而不是狭义的 OOP 意义上的。你可以想到Addable作为类型对的关系。那Addable<int, long>持有并不意味着 int自身与Addable有特殊关系.确实Addable可以用作例如

template<Addable<long> Var>
struct client {
Var var;
};

然后 client<int>带有 Addable<int, long>约束,但这种捷径本质上是语法上的。这是减少样板文件的有用方法,即让我们免于编写 template<typename Var> requires Addable<Var, long> .

考虑到这一点,这里有一些表达式可能接近检查您提到的成员签名,加上 Handle场景:

template<typename Obj>
concept bool Object = requires(Obj obj, Obj const cobj, Handle handle) {
cobj.Foo1();
{ obj.Foo2() } -> Obj&;
obj.Foo3(obj);
// static
Obj::Foo4();
// non-member, possibly friend
Foo4(obj);

{ obj.get(handle) } -> Obj&;
};

(我省略了 Foo5 场景,因为它值得自己提问,这里是 lead 。)

关于C++ 概念 : Some signatures function conversion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40887814/

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