Function template, is it possible to constrain what parameters I can pass?

Hello,

Often I need to define callable as a parameter for my function.

I do it like this:

1
2
3
4
5
template<typename MyCallback>
void DoSomething(MyCallback callback)
{
  callback(data, size);
}


Is it possible to define signature of MyCallback?
For example I would like that MyCallback would be callable with two specific parameters:

MyCallback(uint8_t *data, size_t size);

Is it possible on template level to require from user of my api to pass such parameters?

Thank you.
You may use function. See:

http://www.cplusplus.com/reference/functional/function/?kw=function

Like so:

1
2
3
4
5
template<typename TData>
void DoSomething(const std::function<void(TData,int)> &callback)
{
  callback(data, size);
}
Thanks, but I've asked specifically about templates and enforcing some parameter types.
Use SFINAE std::enable_if https://en.cppreference.com/w/cpp/types/enable_if
with std::is_invocable https://en.cppreference.com/w/cpp/types/is_invocable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <type_traits>
#include <cstdint>

// enable only if MYCALLBACK can be invoked with two arguments of type std::uint8_t* and std::size_t
template < typename MYCALLBACK >
typename std::enable_if< std::is_invocable< MYCALLBACK, std::uint8_t*, std::size_t >::value >::type
DoSomething( MYCALLBACK callback ) { /* ... */ }

int main()
{
    DoSomething( []( const std::uint8_t* p, std::uintmax_t n ) { /* ... */ } ) ; // fine

    // DoSomething( []( int, int ) { /* ... */ } ) ; // *** error: no matching function
}
Mr. Borges, you help is invaluable as always. Thank you for your time and example from which I can learn.
Topic archived. No new replies allowed.