繁体   English   中英

带有自由功能的decltype错误

[英]decltype error with free function

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

#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
                       ^~~

Wandbox网址: https ://wandbox.org/permlink/E7BbGlyQD8FcHr5j

decltype(fun)返回函数类型,而不是fn ptr类型。 您不能“分配”功能,只能“分配功能”。 如果要包装自由函数,则有以下选择:

  1. 取一个函数ptr
  2. 将fun()调用包装在lambda中
  3. 在std :: function <>中包装乐趣(注意:这是一个虚拟调用)

这实际上是不使用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 ++意义上的函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM