Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for documenting std::function parameters

Tags:

c++

When declaring a type using std::function, I find that I miss being able to assign parameter names to the template arguments. For example, I find this plain function pointer type declaration:

typedef void (*ArcCallback)(
  void *object, 
  double x_start, double y_start, 
  double x_finish, double y_finish, 
  double x_center, double y_center, 
  bool counterclockwise);

to be more readable than this std::function type declaration:

typedef std::function<void(
  void *,
  double, double,
  double, double,
  double, double,
  bool)> ArcCallback;

Despite the flexibility that comes with the use of std::function (for example, being able to assign a lambda or the result of a std::bind call), I miss the parameter names. Of course I can add comments to the std::function declaration, but the result is clunky. More importantly, I don't think IDEs would use those comments to provide parameter hints.

How do other experienced C++ practitioners document the purpose of template parameters to std::function? Is there a precedent set by widely-used libraries that heavily use such types?

like image 948
Tim Crews Avatar asked Mar 31 '26 04:03

Tim Crews


1 Answers

For this particular code, the problem isn't so much that std::function has no good way to document parameters, the problem is that 8 parameters is probably too much for any function. Introducing additional types can go a long way toward cleaning this up.

typedef void* CallbackObject;

struct Point {
  double x;
  double y;
};

enum CircularDirection {
  CLOCKWISE,
  COUNTERCLOCKWISE
};

struct ArcCallbackParam {
  CallbackObject object;
  Point start;
  Point finish;
  Point center;
  CircularDirection direction;
};

typedef std::function<void(const ArcCallbackParam&)> ArcCallback;

Edit: I realize this doesn't directly answer your question. To answer your question, I'm not aware of any "solutions" beyond commenting the arguments, but adding types and typedefs can help a lot.

like image 186
Josh Kelley Avatar answered Apr 02 '26 21:04

Josh Kelley