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

Viewed 142

I have a file vector.h with a custom Vector class, where the data type of the vector entries should be restricted to types for which a function f is implemented:

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

template <Vector_Type T>
class Vector {};

Additionally, I have multiple files where the function f is defined for different data types, e.g. the following datatype_int.h header file:

int f(int a) { return 2*a; }

If I include datatype_int.h after vector.h, the compiler complains that the constraint is not satisfied:

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

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

    return 0;
}

This is not a very helpful error message and I would like to avoid being dependent on the order of the includes. However, there is no way to declare the function f for all possible data types T in vector.h, since I do not know which data types will be used.

How can I solve this problem?

1 Answers

I am not sure how workable this design is, but the crux of the issue is that int is a builtin type. If you have a special type that is used to invoke f, you'll be able to delay the lookup of f until instantiation.

For example:

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;
}
Related