2
votes

With C++20 and concepts around the corner I wondered if it will be possible to write a concept to check if a Type has a function with a certain name which takes any number of arbitrary arguments.

Take the following code for example (with GCC's current concept TS syntax):

template <typename T>
concept bool Initializable = requires(T t) {
  { t.init() } ->void;
};

struct S {
  void init() {}
};

static_assert(Initializable<S>);

The concept Initializable checks if a Type implements a void init() function. Now lets assume there is another Type which also has an init function but one which requires arguments, e.g. an int:

struct T {
  void init(int) {}
};

Now in this case the static assertion would fail.

Is there any way to make the Initializable concept ignore the function arguments? This example might seem rather derived, but for something like a generic serializer there might be use-cases for such a concept.

1
What would the point of such a concept be? How would you call init if you don't know how many/what arguments it takes?Barry

1 Answers

3
votes

There is a type trait for that, std::is_member_function_pointer. But if you want that the return type is void too, then you can do both at the same time:

template <typename>
struct mptr_returns_void : std::false_type {};

template <typename T, typename ...Args>
struct mptr_returns_void<void(T::*)(Args...)> : std::true_type {};


template <typename T>
concept Initializable = mptr_returns_void<decltype(&T::init)>::value;