Code Function Signature

I want to create many functions with the same parameters, for example:

const int add(const int a, const int b) { return (a + b); } decltype(add) subtract { return (a - b); } /* many more functions */ 

The goal is that I can easily change parameter types once to change all functions. I know this is possible with macros:

 #define INT_OPERATION(name) const int name (const int a, const int b) INT_OPERATION(add) { return (a + b); } INT_OPERATION(subtract) {return (a - b); } 

However, I do not like the use of macros. Is there a safer way to do this?

+6
source share
4 answers

The signature function cannot be typedef ed. Only function type. Therefore, it is fair to say:

 typedef int INT_OPERATION(int a, int b); 

and then forward declare a function of this type:

 INT_OPERATION Add; 

but , when it comes to defining the function you need to specify for the arguments, so the following expression is not valid

 INT_OPERATION Add { /* No can do */ } 

(as soon as you put the set () after Add , you will declare a function that returns a simple function that is not valid with C ++)

About common types

The same procedure has similar limitations when using tools for general programming. You can declare the following typedef:

 template<typename T> using INT_OPERATION = const T(T const, T const); 

And then use it to declare a function (forward)

 INT_OPERATION<int> add; int main() { std::cout << add(1, 2) << std::endl; return 0; } 

but when it comes to defining it, you must be mandane

 const int add(int const a, int const b) { return a + b; } 

Demo

+3
source

Maybe something like this:

 #include <iostream> #include <functional> typedef std::function<int(int, int)> IntFunction; IntFunction add = [](int a, int b) {return a + b;}; IntFunction substract = [](int a, int b) {return a - b;}; int main(int, char**) { std::cout << add(1, 2) << std::endl; std::cout << substract(1, 2) << std::endl; return 0; } 

Another template code, but worth a try;)

+2
source

If your main problem is to “easily change parameter types”, simply write them in the form of templates so that you never have to change parameter types:

 template <typename T1, typename T2> auto add (const T1 &a, const T2 &b) -> decltype(a + b) { return (a + b); } 

It also handles cases where a and b not of the same type, or where a + b not the same type as a or b .

+1
source

If these are member functions, you can declare their generic type ( typedef const int Fn(int, int) ), declare member functions inside the class using this type:

 Fn add, subtract; 

Then you define them outside the class in the usual way. Does not save the template, but at least means that it will not compile if you make a typo in the definitions.

For an alternative for non-member functions, see the question I'm connected to with some kind of smart way to define function pointers, not functions.

+1
source

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


All Articles