jeudi 25 octobre 2018

Returning data of arbitrary simple types from a function

I'm updating some existing C++ code that dates back about 25 years. The code's got a number of "apply function to collection"-type functions with signatures such as

void *CNode::DoUntil(CNode *aRoot, TestFunc1 aFunc, void *aParam)

where aFunc has the signature

void *(*TestFunc1)(CNode *xNode, void *xParam)

This applies aFunc to each item in a collection until aFunc returns non-NULL. Most of the time, this is used to produce operations such as "find" which return a pointer to the found object, but sometimes, it's operations such as "count", where an integer gets stuffed into the void * return value and pulled back out again by the caller. Needless to say, this is 1) ugly, and 2) causes compilers to scream.

What's a suitably idiomatic way to return data of arbitrary type from a function in this situation? At a bare minimum, it needs to support integers, booleans, and pointers, and because of the compiler I'm using, it can't use any constructs newer than C++ 11.

I don't want to do a major re-write of the code; ideally, I'd just change the functions involved to return a std::any, but that's part of C++ 17, not C++ 11.

Aucun commentaire:

Enregistrer un commentaire