I'm totally new to C++
and I was wondering if there's a way to define n functions which have same return type and parameters type in a single line in order to maintain a DRY code.
I tried looking for a solution online and on SO but I wasn't able to find a proper answer.
myHeader.h
class MyClass{
public:
. . .
private:
. . .
std::vector<Dcel::Vertex*> addVertices(std::vector <Dcel::Vertex*>);
std::vector<Dcel::Vertex*> randomPointsGetter(std::vector<Dcel::Vertex*>);
};
For instance, they both return std::vector<Dcel::Vertex*>
type and take std::vector <Dcel::Vertex*>
as parameters input.
Is it possible to define both of them, or n functions, in the same line? If yes, How?
Thanks in advance.
Is it possible to define both of them, or n functions, in the same line? If yes, How?
All whitespace is treated equally in C++, so sure. Here are two functions declared in the same line:
T function(); T another_function();
If you meant whether you could declare multiple functions in one full-expression, or "share" the return type, then no, that is not possible.
If you dislike the complexity of repeated std::vector<Dcel::Vertex*>
, you can use an alias:
using R = std::vector<Dcel::Vertex*>;
R addVertices(R);
R randomPointsGetter(R);
Edit: This using
declaration is semantically equivalent with typedef
as shown in Josh Kelley's answer.
Using a typedef helps cut down on duplication, although it still doesn't let you define multiple functions on the same line.
typedef std::vector<Dcel::Vertex*> VertexList;
VertexList addVertices(VertexList);
VertexList randomPointsGetter(VertexList);
When the number of functions grows, a macro seems appropriate:
class MyClass {
#define MY_PREFIX_DECL_FN(name) \
std::vector<Dcel::Vertex*> name(std::vector<Dcel::Vertex*>)
MY_PREFIX_DECL_FN(addVertices);
MY_PREFIX_DECL_FN(randomPointsGetter);
MY_PREFIX_DECL_FN(...);
#undef MY_PREFIX_DECL_FN
};
Yes.
You can define N
functions either using std::vector
or std::array
:
std::vector< std::function(std::vector<Dcel::Vertex*>(std::vector <Dcel::Vertex*>)) > my_private_functions;
std::array< std::function(std::vector<Dcel::Vertex*>(std::vector <Dcel::Vertex*>)),N > my_private_functions;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.