How to accept only callable objects in templates except pointer to data members?

135 Views Asked by At

I want to create a templated function which accepts and invokes a callable object(except pointer to data members) with arguments to pass to it. I want the template to only accept the following types:-

  1. Pointers to functions
  2. Pointers to member functions
  3. Lambda
  4. bind expressions
  5. std::function
  6. Functors

Like this...

template< class Function, class... Args >
explicit X( Function&& f, Args&&... args );

But the first argument is accepting any type and I want to create some validation such that it only accept callable objects and throw error(preferably in compile-time) if it invalidates.

1

There are 1 best solutions below

9
On

There's a C++20 concept just for this purpose:

template<class Function, class... Args>
    requires (std::invocable<Function, Args...>
        && !std::is_member_object_pointer_v<Function>)
void X(Function&& f, Args&&... args);

(Edited to add is_member_object_pointer_v due to comments below.)