Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constrain the signature of callable objects in C++?

Tags:

c++

template<typename TCallable>
void Fun(TCallable c){
...
}

How can I indicate that the c in the foregoing code must have some specific signature (let's say int(double, double)) without using std::function?

like image 402
JAH Avatar asked Feb 05 '15 09:02

JAH


2 Answers

Looks like you can just add static_assert(std::is_same<decltype(c(0.0,0.0)), int>::value, "c must take two doubles and return int").

like image 109
MSalters Avatar answered Nov 14 '22 22:11

MSalters


If you want several Fun functions for different Callables, then static_assert() won't help you, but you can use SFINAE, e.g.

// version for int(double,double)
template<typename Callable>
auto Fun(Callable c)
-> typename
   std::enable_if<std::is_same<decltype(c(0.0,0.0)),int>::value>::type
{ /* ... */ }

// version for int(double,double,double)
template<typename Callable>
auto Fun(Callable c)
-> typename
   std::enable_if<std::is_same<decltype(c(0.0,0.0,0.0)),int>::value>::type
{ /* ... */ }
like image 38
Walter Avatar answered Nov 14 '22 21:11

Walter