Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么可以';我是否将函数指针作为模板参数传递给映射?_C++_Templates_Stl_Function Pointers - Fatal编程技术网

C++ 为什么可以';我是否将函数指针作为模板参数传递给映射?

C++ 为什么可以';我是否将函数指针作为模板参数传递给映射?,c++,templates,stl,function-pointers,C++,Templates,Stl,Function Pointers,我目前正在开发一个程序,我想为自定义比较器传递一个指向映射的函数指针。然而,在下面的示例中,verifable至少会产生错误: #include <iostream> #include <map> struct CustomKey{ unsigned a; }; bool compareCustom(const CustomKey &a, const CustomKey &b){ return a.a < b.a; } type

我目前正在开发一个程序,我想为自定义比较器传递一个指向映射的函数指针。然而,在下面的示例中,verifable至少会产生错误:

#include <iostream>
#include <map>

struct CustomKey{
    unsigned a;
};

bool compareCustom(const CustomKey &a, const CustomKey &b){
    return a.a < b.a;
}

typedef decltype(compareCustom) CustomComparator;

int main(){
    std::map<CustomKey, unsigned, CustomComparator> customMap(&compareCustom);
    return 0;
}
#包括
#包括
结构自定义键{
未签名的a;
};
bool compareCustom(const CustomKey&a、const CustomKey&b){
返回a.a

使用GCC或Clang编译上述代码会产生大量非信息模板错误,这些错误完全集中在
std::map
的内部实现上。似乎表明传递函数指针类型是完全有效的。我的代码有什么问题?

传递函数指针是有效的,但传递函数不是

typedef decltype(compareCustom) CustomComparator;
实际上使
CustomComparator
的类型为
bool(const CustomKey&,const CustomKey&)
,这是函数本身,而不是指针

你应使用:

typedef decltype(compareCustom) *CustomComparator;

传递函数指针有效,但传递函数无效

typedef decltype(compareCustom) CustomComparator;
实际上使
CustomComparator
的类型为
bool(const CustomKey&,const CustomKey&)
,这是函数本身,而不是指针

你应使用:

typedef decltype(compareCustom) *CustomComparator;

typedef decltype(&compareCustom)CustomComparator
@Swardfish不仅仅是在需要函数指针的地方给出函数,还导致编译器将其视为函数指针?@john01dav不,函数名在某些情况下会衰减为指向该函数的指针,而是
decltype(functionName)
不是这些情况之一。@MilesBudnek这些情况是什么?@john01dav这是一个隐式转换。如果您正在初始化或分配一个函数指针,函数名将衰减为一个指针来初始化它。这与数组衰减为指向其第一个元素的指针的方式非常相似
@Swardfish不仅仅是在需要函数指针的地方给出函数,还导致编译器将其视为函数指针?@john01dav不,函数名在某些情况下会衰减为指向该函数的指针,而是
decltype(functionName)
不是这些情况之一。@MilesBudnek这些情况是什么?@john01dav这是一个隐式转换。如果您正在初始化或分配一个函数指针,函数名将衰减为一个指针来初始化它。这与数组衰减为指向第一个元素的指针的方式非常相似。