gpt4 book ai didi

c++ - 如何要求约束中存在函数?

转载 作者:行者123 更新时间:2023-12-03 06:49:40 24 4
gpt4 key购买 nike

我有一个文件 vector.h带定制 Vector类,其中 vector 条目的数据类型应限制为函数 f 的类型。实现:

template <typename T>
concept Vector_Type = requires (T a) {
f(a);
};

template <Vector_Type T>
class Vector {};
此外,我有多个文件,其中函数 f为不同的数据类型定义,例如以下 datatype_int.h头文件:
int f(int a) { return 2*a; }
如果我包括 datatype_int.h之后 vector.h ,编译器提示不满足约束:
#include "vector.h"
#include "datatype_int.h"

int main() {
Vector<int> v; // Error: constraints not satisfied

return 0;
}
这不是一个非常有用的错误消息,我想避免依赖于包含的顺序。但是,没有办法声明函数 f适用于所有可能的数据类型 Tvector.h ,因为我不知道将使用哪些数据类型。
我怎么解决这个问题?

最佳答案

我不确定这个设计有多可行,但问题的关键是 int是内置类型。如果您有用于调用 f 的特殊类型,您将能够延迟 f 的查找直到实例化。
例如:

struct enabler{};

template <typename T>
concept Vector_Type = requires (T a) {
f(a, enabler{});
};

template <Vector_Type T>
class Vector {};

int f(int a, enabler = {}) { return 2*a; }

int main() {
Vector<int> v;
return 0;
}

关于c++ - 如何要求约束中存在函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64729027/

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