mardi 21 avril 2020

std::function incomplete type on const function

Consider the following code which works as expected:

#include <iostream>
#include <functional>

struct foo
{
    std::function<int()> get;
};

struct bar
{
    int get()
    {
        return 42;
    }
};

int main()
{
    foo f;
    bar b;
    f.get = std::bind(&bar::get, &b);

    if (f.get())
        std::cout << "f.get(): " << f.get() << std::endl;

    return 0;
}

Now, let's assume that bar::get() is a const member function:

#include <iostream>
#include <functional>

struct foo
{
    std::function<int()const> get;
};

struct bar
{
    int get() const
    {
        return 42;
    }
};

int main()
{
    foo f;
    bar b;
    f.get = std::bind(&bar::get, &b);

    if (f.get())
        std::cout << "f.get(): " << f.get() << std::endl;
}

Using GCC 9.2, this snipped throws the following compiler error:

main.cpp:6:31: error: field 'get' has incomplete type 'std::function<int() const>'
    6 |     std::function<int()const> get;
      |                               ^~~
In file included from /usr/local/include/c++/9.2.0/functional:59,
                 from main.cpp:2:
/usr/local/include/c++/9.2.0/bits/std_function.h:128:11: note: declaration of 'class std::function<int() const>'
  128 |     class function;
      |           ^~~~~~~~

I fail to understand why foo::get has incomplete type. Could somebody point me towards the right direction for understanding this behavior and "fixing" it accordingly? I have the need to bind a const member function to a function pointer.

Aucun commentaire:

Enregistrer un commentaire