为什么此参数包不能接受函数指针?
Why can't this parameter pack accept function pointers?
我正在尝试创建一个充满函数指针的参数包,但是GCC(使用c ++ 17标准(生成了一个deduction failed
错误。为什么?
正如这里所写:
对于指向函数的指针,有效参数是指向具有链接的函数(或计算结果为 null 指针值的常量表达式(的指针。
在我的示例中,情况就是这样(不是吗?
此规则是否对参数包无效?我是否错过了标准中的某些内容?如果是这种情况,我该如何修复我的代码,而无需将函数指针作为函数参数传递(即不声明T run2(T input, Funcs... funcs)
.
// In f.hpp
template<typename T>
T run2(T input)
{
return input;
}
template<typename T, T(*f)(T), class ... Funcs>
T run2(T input)
{
return run2<T, Funcs...>(f(input));
}
// In m.cpp
unsigned add2(unsigned v)
{
return v+2;
}
int main()
{
unsigned a=1;
a = run2<unsigned, add2>(a); // works
a = run2<unsigned, add2, add2>(a); // doesn't work
std::cout << a << std::endl;
return 0;
}
这是我在run2<unsigned, add2, add2>
时遇到的错误(GCC 没有告诉我为什么最后一次尝试实际上失败了(:
m.cpp: In function ‘int main()’:
m.cpp:37:37: error: no matching function for call to ‘run2(unsigned int&)’
a = run2<unsigned, add2, add2>(a);
^
In file included from m.cpp:2:0:
./f.hpp:85:3: note: candidate: template<class T> T run2(T)
T run2(T input)
^
./f.hpp:85:3: note: template argument deduction/substitution failed:
m.cpp:37:37: error: wrong number of template arguments (3, should be 1)
a = run2<unsigned, add2, add2>(a);
^
In file included from m.cpp:2:0:
./f.hpp:109:3: note: candidate: template<class T, T (* f)(T), class ... Funcs> T run2(T)
T run2(T input)
^
./f.hpp:109:3: note: template argument deduction/substitution failed:
您声明了一个类型参数包,class... Funcs
。不能将函数指针作为类型参数的参数传递,因为它们是值,而不是类型。相反,您需要声明run2
模板,以便它具有函数指针模板参数包。执行此操作的语法如下:
template<typename T, T(*f)(T), T(*...fs)(T)>
T run2(T input)
{
return run2<T, fs...>(f(input));
}
(规则是...
是声明符 id的一部分,并且位于标识符(即fs
(之前。
包fs
可以接受一个或多个类型为T (*)(T)
的函数指针。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针