#include <functional>
void toggleOk(bool& b) { b = !b; }
void toggleBroken(bool b) { b = !b; }
void toggleInt(int i) { i = !i; }
void tooManyParams(bool b, int i) { i = !b; }
int main()
{
typedef std::function<void(bool&)> CallbackType;
typedef std::function<void(bool)> WrongCallbackType;
CallbackType cb1 = [](bool b) { b = !b; }; // Should throw error - missing reference
CallbackType cb2 = toggleOk; // Ok
CallbackType cb3 = toggleBroken; // Should throw error - missing reference
CallbackType cb4 = toggleInt; // Should throw error - integer instead of bool
WrongCallbackType cb5 = toggleBroken; // Ok
CallbackType cb6 = cb5; // Type checking not even applying between std::functions
CallbackType cb7 = tooManyParams; // Only this statement throws error
return 0;
}
考虑上面的示例,它创建了许多具有对
bool
类型参数的引用的回调函数。除了最后一个回调函数 cb7
外,这段代码可以编译和运行得很好,即使大部分存储在回调对象中的函数与参数的引用或类型不匹配。我在使用 VS19/C++20 存储在
std::function
中的 lambda 表达式时遇到了这种情况,但是我尝试了两个不同的 G++ 编译器(用于 Windows),并启用了额外的诊断,同时使用了 C++17/C++2a,却没有报告任何警告。我的问题是 - 这是一种预期的行为还是一个错误?为什么?
bool b{}; toggleInt(b);
,并且它可以编译(除了tooManyParams
)。 - Jarod42