【发布时间】:2020-04-21 09:51:10
【问题描述】:
考虑以下按预期工作的代码:
#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;
}
现在,假设 bar::get() 是一个 const 成员函数:
#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;
}
使用 GCC 9.2,此片段会引发以下编译器错误:
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;
| ^~~~~~~~
我不明白为什么foo::get 的类型不完整。
有人可以指出我理解这种行为并相应地“修复”它的正确方向吗?
我需要将 const 成员函数绑定到函数指针。
【问题讨论】:
-
所以你想要
const std::function<int()> get;?或者你想要int (bar::*get)() const;? constness 在std::bind而非std::function进行检查。
标签: c++ c++11 stl std-function