C++ allows non-type template parameters to be of pointer, including function pointer, type. I recently asked a question about what this is useful for, and this is a follow up to one of the answers.
Is it posible to deduce the value of a function pointer template parameter, from a function argument that is the function pointer in question? For example:
using VoidFunction = void(*)();
template <VoidFunction F>
void templ(VoidFunction);
...
void func(); // a VoidFunction
...
templ<func>(func); // works, but I have to specify the template parameter explicitly
templ(func); // <-- I would like to be able to do this
Is there a way to get this deduction to happen? It seems technically possible from a compiler implementer's point of view, as long as the function argument can be resolved to a function in the code at compile time.
If you're wondering about the motivation behind this, see the comments under this answer, particularly a possible optimization for the implementation of std::bind()
.
EDIT: I realize that I could simply remove the function argument and use the template argument, as in templ<func>()
. My only purpose of adding in the function argument was to try to avoid having to pass the template argument.
I guess what I really want, is to also deduce the type of the function pointer, as in:
template <typename Function, Function F>
void templ(/* something */);
and then be able to call
templ(func);
or
templ<func>();
and have both the type and value be deduced from a single mention of the function pointer.
Hope that makes more sense now.
template<std::size_t N> void foo(std::size_t i) {int arr[N]; /*fill*/ return arr[i];}
. I would definitely want an error if I happened to forget the template argument when this deduction could be done. – Lingotempl<func>();
enough? – LingoT
intemplate<using typename T, T t>
, but I don't think it made it in. – Lingotemplate <typename Function> templ(Function func);
? – Fogarty