“a variable declared with an auto specifier cannot appear in its own initializer”

早过忘川 提交于 2020-04-11 12:26:23

问题


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;
}

回答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.



来源:https://stackoverflow.com/questions/44857390/a-variable-declared-with-an-auto-specifier-cannot-appear-in-its-own-initializer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!