gpt4 book ai didi

c++ - 可以将模板瞬间的地址作为指向某个函数的函数的指针传递给函数吗?

转载 作者:行者123 更新时间:2023-12-01 14:49:04 25 4
gpt4 key购买 nike

我有以下代码编译没有任何问题

#include<iostream>
#include<vector>

template<typename T>
void compare(const std::vector<T> &v1, const std::vector<T> &v2, void(*func)(const int&,const int&,const size_t&))
{
size_t minLen{v1.size() < v2.size() ? v1.size() : v2.size()};

for(size_t index{}; index<minLen; index++)
func(v1[index],v2[index],index);

}

template<typename T>
void matcher(const T& val1,const T& val2,const size_t& index)
{
if(val1==val2) std::cout<<"v1 and v2 are equal at index "<<index<<"\n";

}


int main()
{
std::vector v1={1,5,-9,-8};
std::vector v2={1,5,-9,-80,45};
compare(v1,v2,&(matcher<int>));
return 0;
}

现在我有以下问题:是 compare(v1,v2,&(matcher<int>));相当于 compare(v1,v2,&matcher);为什么

编辑

当我删除 const之前 index匹配器中的var,编译器显示如下错误
temp.cpp(85): error C2664: 'void compare1<int>(const std::vector<int,std::allocator<int>> &,const std::vector<int,std::allocator<int>> &,void (__cdecl *)(const int &,const int &,const size_t &))': cannot convert argument 3 from 'void (__cdecl *)(const T &,const T &,size_t &)' to 'void (__cdecl *)(const int &,const int &,const size_t &)'
temp.cpp(85): note: None of the functions with this name in scope match the target type
temp.cpp(64): note: see declaration of 'compare1'

编译器说
'void (__cdecl *)(const T &,const T &,size_t &)' to 'void (__cdecl *)(const int &,const int &,const size_t &)'

它没有说
'void (__cdecl *)(const int &,const int &,size_t &)' to 'void (__cdecl *)(const int &,const int &,const size_t &)'

最佳答案

compare(v1,v2,&matcher);工作是因为 template argument deduction .

Template argument deduction is used when taking an address of a overload set, which includes function templates.





If the function name names a function template, then, first, template argument deduction is done, and if it succeeds, it produces a single template specialization which is added to the set of overloads to consider.


compare的第三个函数参数类型是 void(*func)(const int&,const int&,const size_t&) ,当通过 &matcher ,模板参数 Tmatcher推导出为 int ,效果与显式指定模板参数为 matcher<int> 相同.

BTW:打印出什么样的消息取决于编译器的实现;例如 clang给出不同的。

关于c++ - 可以将模板瞬间的地址作为指向某个函数的函数的指针传递给函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59571866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com