c++ - 自由函数的 decltype 错误

标签 c++

我在玩 decltype 时发现了奇怪的东西。为什么在尝试 decltype 自由函数时会出现此错误?它适用于 lambda,但不适用于自由函数。我在这里做错了什么?

#include <iostream>
using namespace std;

int fun()
{
    cout << "inside fun" << endl;
    return 1;
}

int main()
{
    decltype(fun()) x = 2;
    cout << x << endl;

    auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
    decltype(lambda) l = lambda;
    l();

    decltype(fun) f = fun; // ERROR
    f();
}

错误是:

prog.cc: In function 'int main()':
prog.cc:19:19: warning: declaration of 'int f()' has 'extern' and is initialized
     decltype(fun) f = fun; // ERROR
                   ^
prog.cc:19:23: error: function 'int f()' is initialized like a variable
     decltype(fun) f = fun; // ERROR
                       ^~~

魔盒网址:https://wandbox.org/permlink/E7BbGlyQD8FcHr5j

最佳答案

这里在不使用 decltype 的情况下本质上是相同的错误:

#include <iostream>
using namespace std;

int fun()
{
    cout << "inside fun" << endl;
    return 1;
}

int main()
{
    // was: decltype(fun()) x = 2;
    int x = 2;
    cout << x << endl;

    auto lambda = [] () -> int { cout << "inside lambda" << endl; return 3; };
    decltype(lambda) l = lambda;
    l();

    typedef int fn_type();
    fn_type* f = fun;  // no problem
    fn_type g = fun; // ERROR
    f();
}

您已将 f 声明为 int() 类型,即您正试图将该函数复制到一个新变量中,而 C++ 不支持该变量(函数不是一等对象)。允许创建一个函数指针,这可能是您想要的,并直接从 fun 赋值,这将在该上下文中自动被视为函数指针。

这不会发生在 lambda 上,因为它们隐式声明了一个新类(通常意义上的常规 class)。它们的行为函数,因为它们有一个重载的operator() 方法,但它们实际上并不是传统 C++ 意义上的函数。

关于c++ - 自由函数的 decltype 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219806/

相关文章:

c++ - CentOS中音频文件ds2格式转换为wav

c++ - c/c++中的DNS查询

c++ - 发送没有文件描述符的文件

c++ - MFC从文件中读取unicode字符串到字符串中

c++ - 归一化整数到/从 float 转换

android - 使用 FFmpeg 编码时处理原始数据的正确方法

c++函数返回一个枚举?

c++ - 与多个用户一起处理 SEAL 密文

c++ - 使用eclipse的c++中的简单hello world获取错误bin bash权限被拒绝

c++ - 访问 'padded'字节是不是UB?