为什么 std::bind 静态类型检查传递给函数的参数?
Why does std::bind statically type check arguments passed to the function?
不完全是一个问题,但更像是一个沉思......我写了一个程序来测试 'std::bind' 如何将参数传递给被绑定的函数。在这种情况下,C++ 编译器似乎执行静态类型检查:
#include <iostream>
#include <functional>
void take_int(const int *a)
{
if (a)
{
std::cout << "a is " << *a << std::endl;
}
else
{
std::cout << "null" << std::endl;
}
}
int main()
{
int *a = new(int);
*a = 4;
take_int(NULL); //prints 'null'
auto fn = std::bind(take_int, NULL); //fails to compile
fn();
return 0;
}
直接用NULL调用函数似乎不一致,但在编译时通过std::bind调用函数却失败了。
我猜 std::bind 正在使用更现代的 C++ 功能来选择强制执行此操作?
这是因为您使用的是已弃用的 NULL
。相反,您应该使用 nullptr
.
如果您在片段中使用 nullptr
,代码将按预期进行编译。
你需要记住
NULL
can be an integer literal with value zero, or a prvalue of type
std::nullptr_t
在你的例子中,它是整数文字。当您使用该值调用函数时,它会转换为指针 - 这就是直接调用函数有效的原因。
您的编译器将 NULL
定义为 0
,作为文字可以隐式转换为 int*
。这就是为什么您的第一个电话是成功的。
但是 std::bind()
将为 <void (&)(const int *),int>
生成一个无法调用的对象,因为 int
类型的变量无法隐式转换为 int*
.
不完全是一个问题,但更像是一个沉思......我写了一个程序来测试 'std::bind' 如何将参数传递给被绑定的函数。在这种情况下,C++ 编译器似乎执行静态类型检查:
#include <iostream>
#include <functional>
void take_int(const int *a)
{
if (a)
{
std::cout << "a is " << *a << std::endl;
}
else
{
std::cout << "null" << std::endl;
}
}
int main()
{
int *a = new(int);
*a = 4;
take_int(NULL); //prints 'null'
auto fn = std::bind(take_int, NULL); //fails to compile
fn();
return 0;
}
直接用NULL调用函数似乎不一致,但在编译时通过std::bind调用函数却失败了。
我猜 std::bind 正在使用更现代的 C++ 功能来选择强制执行此操作?
这是因为您使用的是已弃用的 NULL
。相反,您应该使用 nullptr
.
如果您在片段中使用 nullptr
,代码将按预期进行编译。
你需要记住
NULL
can be an integer literal with value zero, or a prvalue of type std::nullptr_t
在你的例子中,它是整数文字。当您使用该值调用函数时,它会转换为指针 - 这就是直接调用函数有效的原因。
您的编译器将 NULL
定义为 0
,作为文字可以隐式转换为 int*
。这就是为什么您的第一个电话是成功的。
但是 std::bind()
将为 <void (&)(const int *),int>
生成一个无法调用的对象,因为 int
类型的变量无法隐式转换为 int*
.