I would like to pass a function pointer from an array of function pointers as a template argument. My code seems to compile using MSVC even though Intellisense complains that something is wrong. Both gcc and clang fail to compile the code.
Consider the following example:
static void test() {}
using FunctionPointer = void(*)();
static constexpr FunctionPointer functions[] = { test };
template <FunctionPointer function>
static void wrapper_function()
{
function();
}
int main()
{
test(); // OK
functions[0](); // OK
wrapper_function<test>(); // OK
wrapper_function<functions[0]>(); // Error?
}
MSVC compiles the code but Intellisense gives the following error: invalid nontype template argument of type "const FunctionPointer"
gcc fails to compile with the following message:
<source>: In function 'int main()':
<source>:19:33: error: no matching function for call to 'wrapper_function<functions[0]>()'
19 | wrapper_function<functions[0]>(); // Error?
| ^
<source>:8:13: note: candidate: 'template<void (* function)()> void wrapper_function()'
8 | static void wrapper_function()
| ^~~~~~~~~~~~~~~~
<source>:8:13: note: template argument deduction/substitution failed:
<source>:19:30: error: '(FunctionPointer)functions[0]' is not a valid template argument for type 'void (*)()'
19 | wrapper_function<functions[0]>(); // Error?
| ~~~~~~~~~~~^
<source>:19:30: note: it must be the address of a function with external linkage
clang fails to compile with the following message:
<source>:19:2: error: no matching function for call to 'wrapper_function'
wrapper_function<functions[0]>(); // Error?
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<source>:8:13: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'function'
static void wrapper_function()
^
1 error generated.
Questions:
Is wrapper_function<functions[0]>(); valid or not?
If it isn't, is there anything I can do to pass functions[0] as a template argument to wrapper_function? My goal is to construct a new array of function pointers at compile time, with the content { wrapper_function<functions[0]>, ..., wrapper_function<functions[std::size(functions) - 1]> }.
wrapper_function<decltype(functions[0])>()doesn't compile.