Here is some code where a function template takes a function to call as the template non-type argument:
template <class R, R func() >
auto Call() -> R
{
return func();
}
int f() { return 1; }
int main()
{
Call<int, f>(); // OK
Call<f>(); // Error
}
Is there any way to make this be callable without the need to repeat the function return type, as in Call<f>()
?
It can be done via the preprocessor, #define CALL(f) Call<decltype(f()), f>
, but I would like to know if it can be done without the preprocessor.
This is what auto
template parameters were designed to solve (C++17 and later).
#include <cstdio>
#include <type_traits>
template <auto Fn>
auto Call() -> decltype(Fn()) {
return Fn();
}
int f() { return 1; }
int main() {
printf("%d\n", Call<f>());
}