Use concepts to check if a global function exists

679 Views Asked by At

I can create a concept that checks the existence of a member function called to_string() that returns a std::string in a struct/class.

template<typename T>
concept method_to_string = requires(T v)
{
    { v.to_string() } -> std::same_as<std::string>;
};

I would like create a concept that checks the existence of a global function called to_string that accepts a T, and returns a std::string. I fail to do that. I use gcc 10.2 as compiler.

My guess is that i would look like this, but it fails:

template<typename T>
concept function_to_string = requires(T v)
{
    to_string(const T&) -> std::same_as<std::string>;
};
1

There are 1 best solutions below

3
On BEST ANSWER

This appears to work:

template<typename T>
concept method_to_string = requires(T v)
{
    { to_string(v) } -> std::same_as<std::string>;
};

https://gcc.godbolt.org/z/7WdTjf