我有两个问题
setEvalFunction 的这两个声明是否等效 对于
using EvalFunctionPtr = T (*)(const std::vector<T>&);
?a) void setEvalFunction(const EvalFunctionPtr& evalFunc); b) void setEvalFunction(T (* const &evalFunc)(const std::vector<T>&));
以下参数之间有什么区别(因为两者似乎都可以正常工作)。
a) T (* const &evalFunc)(const std::vector<T>&) b) T (* const &evalFunc)(const std::vector<T>&)&
我想要等同于 1 a) 的东西,即传递对常量函数指针的引用,但不使用一些额外的定义,如 using EvalFunctionPtr = ...
.
最佳答案
- Are both of these declarations of
setEvalFunction
equivalent
是的。
- What is the difference between the following parameters (since both seem to work fine).
我确实相信 2. b) R (* const & fptr)(/*args*/)&
格式错误,因为(非成员)函数指针不能有 ref -限定符,这是最后的 &
表示的。但是,可能由于编译器错误,我的 GCC 确实接受它并将其解析为与 R (* const & fptr)(/*args*/)
相同的方式。编辑:clang 正确地拒绝编译它。
I want to have something equivalent to 1 a), i.e. passing a reference to a constant function pointer, but without using some extra definition like using
EvalFunctionPtr = ....
这是对 1.b 的非常恰当的描述。
Passing the value of a function pointer is passing a 64bit integer (in my case of a 64 bit system), which is not the same as passing the reference of a function pointer, since the reference is applied by the compiler, and takes zero time during runtime. But the copy of an integer takes time, doesn't it?
传递引用在运行时不会花费零时间。事实上,将引用参数传递给函数实际上是复制指针的地址(在你的情况下可能是 64 位)并取消引用它(假设你实际访问了引用),这不仅仅是在传递的情况下复制按值的指针。如果优化器对函数进行了内联扩展,那么这两种方式可能都没有区别。
关于c++ - c++中函数指针语法的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40322298/