C++ 对函数的引用在调用中崩溃

标签 c++ function templates reference

我使用模板化引用通过函数类型引用来捕获函数,但是当我尝试通过 param() 调用时它崩溃了(使用 Apple LLVM 版本 9.0.0 (clang-900.0.38),x86_64-苹果-darwin17.2.0)

#include <iostream>
#include <typeinfo>

int doit(int a, int b) {
    return a+b;
}

template <typename T>
void test(T & param) {
    std::cout << typeid(T).name() << " ";
    std::cout << typeid(param).name() << " ";
    std::cout << param(3,5);
}

int main()
{
    test(doit);
}

crash

但是根据 Scott Meyers 的书“函数类型可以衰减为函数指针”:

void someFunc(int, double); // someFunc is a function; type is void(int, double)

template<typename T>
void f1(T param);       // in f1, param passed by value


template<typename T>
void f2(T& param);      // in f2, param passed by ref

f1(someFunc);       // param deduced as ptr-to-func; type is void (*)(int, double)
f2(someFunc);       // param deduced as ref-to-func; type is void (&)(int, double)

所以我希望参数是一个函数引用类型并由它调用。 怎么了?

更新:看起来这是一个 Clang 优化器错误! FIX:在调用参数之前评估参数的值 - 修复了这种情况!

std::cout << param << " - " << (*param)(3,5);

最佳答案

这似乎是一个 Clang 优化器错误! FIX:在调用参数之前评估参数的值 - 修复了这种情况!

std::cout << param << " - " << (*param)(3,5);

关于C++ 对函数的引用在调用中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47363242/

相关文章:

c++ - 如何将paraview源码编译成Qt工程(.pro)?

c++ - 如何在 C++20 范围内将投影与变换结合起来

c++ - 两个3D点云变换矩阵

c++ - 编写图形类时出现此错误是什么意思?

python - 将多个参数传递给函数的最有效方法?

c++ - 使用Clang LibTooling扫描已调用模板化父类中的本地类的C++源

谁能把这个翻译成Python?

C 参数数组声明符

c++ - 在 Typedef 中转换模板参数

c++ - 在 C++ 中重命名(别名/转发)函数的最佳方法是什么?