constexpr parametrized function pointer
Sort of.
This:
obj1->ComputeStatistics(getHistogramLambda("obj1"));
Won't work for the reasons you point out - you need to capture state. And then, we can't write this:
obj1->ComputeStatistics(getHistogramLambda<"obj1">());
Because while we can have template parameters of type const char*
we can't have them bind to string literals. You could do it this way:
template <const char* name>
constexpr auto getHistogramLambda() {
return [](const auto& v) {return histogram(name, v);};
}
const char p[] = "obj1";
obj1->ComputeStatistics(getHistogramLambda<p>());
Which is pretty awkward because you need to introduce the extra variable for each invocation. In C++20, we'll be able to write a class type that has as its template paramater a fixed string, which will allow getHistogramLambda<"obj1">
to work, just in a slightly different way.
Until then, the best way currently is probably to use a UDL to capture the individual characters as template parameters of some class type:
template <char... Cs>
constexpr auto getHistogramLambda(X<Cs...>) {
static constexpr char name[] = {Cs..., '\0'};
return [](const auto& v) { return histogram(name, v);};
}
obj->ComputeStatistic(getHistogramLambda("obj1"_udl));
The intent here is that "obj"_udl
is an object of type X<'o', 'b', 'j', '1'>
- and then we reconstruct the string within the body of the function template in a way that still does not require capture.
Is this worth it to avoid the duplication? Maybe.