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

How to require the existence of a function in a constraint?

我有一个带有自定义 Vector class 的文件 vector.h,其中矢量条目的数据类型应限制为函数 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; }

如果我在 vector.h 之后包含 datatype_int.h,编译器会抱怨不满足约束:

#include "vector.h"
#include "datatype_int.h"

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

    return 0;
}

这不是一个非常有用的错误消息,我想避免依赖包含的顺序。但是,无法为 vector.h 中所有可能的数据类型 T 声明函数 f,因为我不知道将使用哪些数据类型。

我该如何解决这个问题?

我不确定这种设计的可行性如何,但问题的症结在于 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;
}