We have a helper function in our codebase to concatenate two (Windows) path strings:
CString AppendPath(CString const& part1, CString const& part2);
It is often used in this way:
const CString filePath = AppendPath(AppendPath(AppendPath(base, toplevel), sub1), filename);
This is rather acceptable, but it got me wondering if there is some possibility in C++ (or C++0x) to use a (template?) function to chain binary function calls together.
That is, given a function T f(T arg1, T arg2) is it possible to write a function T ncall(FnT fn, T arg1, T arg2, T arg3, ...) that will call f like in my example above and return the result?
// could roughly look like this with my example:
const CString filePath = ncall(&AppendPath, base, toplevel, sub1, filename);
Please, this question is about the transformation and not about the best way to handle or concatenate path strings!
Edit: Thanks to deft_code‘s answer for providing the correct term for what I was asking for: Fold (higher-order function). (Note that I have settled on accepting the answer of Matthieu because his solution does not require C++0x.)
Without C++0x, it’s also possible to use chaining (I don’t recommend overloading the comma operator, the syntax gets weird).
The syntax is somewhat different, but very close:
This is done simply by creating a temporary object that will perform the catenation through an overload of
operator()and which will be implicitly convertible throughoperator CString() const.Then, you tweak
AppendPathto return such an object:(Note, actually you could directly name it
AppendPath)Making it generic as per @Martin’s suggestion:
Code validated on ideone.