Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy function signature

Tags:

c++

I wish 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 purpose being that I am able to easily change the types of the parameters once to change all of the functions. I know that this is possible with macros as so:

#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 dislike the use of macros. Is there a safer way of doing this?

like image 339
nwn Avatar asked Jul 05 '14 06:07

nwn


1 Answers

A function signature cannot be typedefed. Only a function's type. So it's valid to say :

typedef int INT_OPERATION(int a, int b);

and then forward declare a function having this type :

INT_OPERATION Add;

but when it comes to defining the function you'd have to specify arguments, so the follwing is invalid

INT_OPERATION Add { /* No can do */ }

(as soon as you place a set of () after Add you'll be declaring a function returning a plain function which is not valid C++)

On generic types

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

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

And then use it for a function (forward) declaration

INT_OPERATION<int> add;

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

but when it comes to defining it, you'd have to be mandane

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

Demo

like image 64
Nikos Athanasiou Avatar answered Oct 06 '22 00:10

Nikos Athanasiou