【发布时间】:2020-01-17 13:13:55
【问题描述】:
我想将函数指针数组中的函数指针作为模板参数传递。即使 Intellisense 抱怨有问题,我的代码似乎也可以使用 MSVC 进行编译。 gcc 和 clang 都无法编译代码。
考虑以下示例:
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 编译代码,但 Intellisense 给出以下错误:invalid nontype template argument of type "const FunctionPointer"
gcc 无法编译并显示以下消息:
<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 无法编译并显示以下消息:
<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.
问题:
wrapper_function<functions[0]>(); 是否有效?
如果不是,我可以做些什么来将functions[0] 作为模板参数传递给wrapper_function?我的目标是在编译时构造一个新的函数指针数组,内容为{ wrapper_function<functions[0]>, ..., wrapper_function<functions[std::size(functions) - 1]> }。
【问题讨论】:
-
嗯,这很有趣,我认为问题在于您使用的是值(指针)而不是类型。但即使
wrapper_function<decltype(functions[0])>()也无法编译。 -
似乎可以在 C++17 中工作...现在来寻找标准语言的区别...