How to limit the signature of called objects in C ++?

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

How can I indicate that c in the previous code should have a specific signature (for example, int(double, double) ) without using std :: function?

+6
source share
2 answers

It 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") .

+7
source

If you need several Fun functions for different Callable s, then static_assert() will not help you, but you can use SFINAE, for example

 // 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 { /* ... */ } 
+4
source

Source: https://habr.com/ru/post/982028/


All Articles