简体   繁体   中英

decltype error with free function

I was playing with decltype and found strange thing. Why do I have this error when trying to decltype a free function? It works well with lambdas, but not with a free function. What do I do wrong here?

#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();
}

The error is:

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 URL: https://wandbox.org/permlink/E7BbGlyQD8FcHr5j

decltype(fun) returns the function type, not the fn ptr type. You can't 'assign' a function, only a function ptr. If you want to wrap a free function, you have these choices:

  1. Take a function ptr
  2. Wrap the fun() call in a lambda
  3. Wrap fun in std::function<> (note: this is a virtual call)

Here is essentially the same error without using 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();
}

You have declared f to be of type int() ie it's like you're trying to copy the function into a new variable, which C++ does not support (functions are not first-class objects). It's permissible to create a function pointer, which is probably what you want, and assign directly from fun , which will be automatically treated as a function pointer in that context.

This doesn't happen for lambdas because they implicitly declare a new class (just a regular class in the usual sense). They act like functions because they have an overloaded operator() method, but they are not actually functions in the traditional C++ sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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