I am in the middle of writing some generic code for a future library. I came across the following problem inside a template function. Consider the code below:
Some specialization, somewhere, is necessary. But the goal here is to avoid specializing the function itself. However, you can specialize a helper class.
Tested with gcc 9.1 with -std=c++17
.
#include
#include
template
struct return_value {
T val;
template
return_value(F &&f, Args && ...args)
: val{f(std::forward(args)...)}
{
}
T value() const
{
return val;
}
};
template<>
struct return_value {
template
return_value(F &&f, Args && ...args)
{
f(std::forward(args)...);
}
void value() const
{
}
};
template
auto foo(F &&f)
{
return_value()(2, 4))> r{f, 2, 4};
// Something
return r.value();
}
int main()
{
foo( [](int a, int b) { return; });
std::cout << foo( [](int a, int b) { return a+b; }) << std::endl;
}