指向功能和std ::功能:第一个编译而不是第二个指针
Pointer to function and std::function : the first one compiles and not the second one?
我对函数的指针不熟悉,目前正在进行一些测试。但是在以下程序中,我不明白为什么第一个版本有效,以及为什么第二版不编译。正确的语法是什么?
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
template<typename Type>
void display(const std::vector<Type>& v)
{
if (!v.empty()) {
for (unsigned int i = 0; i < v.size()-1; ++i)
std::cout<<v[i]<<" ";
std::cout<<v[v.size()-1];
}
}
// Compiles
template<typename Type>
void apply1(std::vector<Type>& v, void(f)(Type*, Type*, Type))
{
f(&*v.begin(), &*v.end(), 0);
}
// Does not compile
template<typename Type>
void apply2(std::vector<Type>& v, std::function<void(Type*, Type*, Type)> f)
{
f(&*v.begin(), &*v.end(), 0);
}
int main()
{
std::vector<double> v = {1., 2., 3., 4., 5., 6.};
display(v); std::cout<<std::endl;
apply1(v, std::iota);
display(v); std::cout<<std::endl;
apply2(v, std::iota);
display(v); std::cout<<std::endl;
return 0;
}
错误如下:
error: cannot resolve overloaded function 'iota' based on conversion to type 'std::function<void(double*, double*, double)>'
功能指针提供我所说的转换上下文。它明确说明了哪种过载是指std::function
。std::function
的构造函数接收任何可呼叫的实体,因此,没有任何上下文来消除歧义哪种超载。另请参阅此问题。
要手动放弃歧义,要么施放功能指针
apply2(v, static_cast<void(*)(double*,double*,double)>(std::iota));
或使用命名函数指针
void (*iota)(double*, double*, double) = std::iota;
apply2(v, iota);
或使用lambda
apply2(v, [](double* f, double* l, double d){ std::iota(f, l, d); });
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 使第二个类的构造函数成为第一个类中的友元函数
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- 为什么第一个代码块产生垃圾值,而第二个代码块将类成员的值相加?
- 打印无序映射的第二个元素,即集合
- C++ std::enable_if - 第二个参数的功能
- C 功能模板指定第二个模板参数类型
- 模板的C 功能将第一个参数设置为第二个参数为默认参数
- 该功能的第二个调用中的分割故障
- 指向功能和std ::功能:第一个编译而不是第二个指针
- 程序运行,但程序中的第二个功能不打印?输出中没有错误