3

It seems like there's an error when using the trailing return type in the function pointer declaration for Func_ptr. I know I can do it if I put the declaration and initialization in the same statement or simply use the standard declaration by specifying the return type directly, but I want to understand the language's limitations, so can someone please explain what this error means in the code below:

"a variable declared with an auto type specifier cannot appear in its own initializer"

#include <utility>
#include <iostream>

int Func(const std::pair<int, int>& p)
{
    std::cout << p.first << "->" << p.second << std::endl;
    return 1;
}

int main()
{
    auto (*Func_ptr)(const std::pair<int, int>& p) -> int;
    //Error below, Func_ptr underlined, "a variable declared with the auto
    //specifier cannot appear in its own initializer
    Func_ptr = Func;
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Quoc-Minh
  • 113
  • 3
  • 9

1 Answers1

1

Problem is that variable is declared in C++03 style and function format in C++11 way. Make it uniform and it will work.

// the old way
int (*Func_ptr1)(const std::pair<int, int>& p);

// the C++11
auto func_ptr2 = &Func;

Here is example. What is more interesting Clang is able to handle mixture.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • 3
    All compilers I know handle this "mixture" without any problems. There's nothing unusual in it. Why do you see it as "more interesting"? Also, your initial statement is backwards. – AnT stands with Russia Jul 01 '17 at 07:03
  • Yes, I know your syntax works, I was just trying out different syntax possibilities to better understand C++ boundaries. Thank you for taking the time to help! – Quoc-Minh Jul 01 '17 at 18:38