c++ - c++中函数指针语法的理解

标签 c++ c++11 function-pointers

我有两个问题

  1. setEvalFunction 的这两个声明是否等效 对于 using EvalFunctionPtr = T (*)(const std::vector<T>&);

    a) void setEvalFunction(const EvalFunctionPtr& evalFunc);
    
    b) void setEvalFunction(T (* const &evalFunc)(const std::vector<T>&));
    
  2. 以下参数之间有什么区别(因为两者似乎都可以正常工作)。

    a) T (* const &evalFunc)(const std::vector<T>&)
    
    b) T (* const &evalFunc)(const std::vector<T>&)&
    

我想要等同于 1 a) 的东西,即传递对常量函数指针的引用,但不使用一些额外的定义,如 using EvalFunctionPtr = ... .

最佳答案

  1. Are both of these declarations of setEvalFunction equivalent

是的。

  1. 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/

相关文章:

c# - OpenCV C++ vector DMatch 到 C#

c++ - 在 C++ 复 vector 的每个元素上调用 conj() 函数

c++ - 更改调用约定

c - qsort 和 bsearch 函数.. ."pointer"

c++ - 二维数组输出一个连续的行

c++ - 从 C++ 调用 C 函数时,如何告诉 gcc 放宽对类型转换的限制?

c++ - 一个有效的程序被 man7.org 宣布为无效

printing - char16_t 打印

c++ - 为什么我不能按值将右值 std::stringstream 传递给函数?

c++ - 实现 C++ 状态机。如何解决 Wpmf 转换警告?