带函数指针的auto说明符 - C++

ove*_*nge 0 c++ c++14

下面的代码有auto函数指针的参数(带说明符),

void g( bool(*fptr)(const auto) ){
  //
}

bool f(const int a){
  //
}
int main(int argc, char *argv[])
{
  g(&f); // Error
}
Run Code Online (Sandbox Code Playgroud)

工作良好.


有了这段代码,

bool k(const auto); // Compiler accepts declaration with auto specifier
auto h(auto& output, const auto& value) // Compiler accepts definition with auto specifier
{
   // output << value << "\n";
}
typedef bool(*fptr)(const auto); // Error 
void g( fptr f ){
  //
}

bool f(const int a){
  //
}
int main(int argc, char *argv[])
{
  g(&f);
}
Run Code Online (Sandbox Code Playgroud)

g++ -std=c++14 说, error: non-function ‘fptr’ declared as implicit template


题:

为什么C++编译器不允许auto使用函数指针?

Rak*_*111 5

auto 在函数参数中是一个gcc扩展,虽然它将在Concepts TS合并时标准化.

我从来没有使用过这个扩展,但这可能只是模板声明的捷径,即

void g( bool(*fptr)(const auto) ) {}

template<typename T>
void g( bool(*fptr)(const T) ) {}
Run Code Online (Sandbox Code Playgroud)

两者都是等价的.您不能在typedef声明中使用模板,您必须使用using声明:

using fptr = bool(*)(const auto); // ok
Run Code Online (Sandbox Code Playgroud)

由于某种原因,代码仍然无法编译,因为它无法转换decltype(&f)(即a bool(*)(int))fptr.那是扩展的错.使用标准C++,您的代码编译得很好:

template<typename T>
using fptr = bool(*)(const T);

template<typename T>
void g( fptr<T> fa ) {}
Run Code Online (Sandbox Code Playgroud)