我在处理某些代码时遇到问题,我需要在其中通过多层函数传递指针。指针可以为 null,因此对于 nullptr 的情况,我对最终函数进行了重载。概念上我有这样的东西:
void test_ptr(std::nullptr_t)
{
std::cout << "nullptr" << std::endl;
}
void test_ptr(double *d)
{
std::cout << *d << std::endl;
}
void test(double *d)
{
test_ptr(d);
}
int main()
{
test(nullptr);
}
对我来说,理想的行为是,如果 test
调用 test_ptr
的第一个版本,但事实并非如此。是否有机会操纵 test
使其调用“正确的”版本?
最佳答案
你需要一个函数模板:
void test_ptr(std::nullptr_t)
{
std::cout << "nullptr" << std::endl;
}
void test_ptr(double *d)
{
std::cout << *d << std::endl;
}
template<typename T>
void test(T d)
{
test_ptr(d);
}
int main()
{
test(nullptr);
}
在您的代码中,参数是 double*
,无论它是从什么类型转换而来的。
确保 T
是指针类型的 static_assert
也可能是有序的:
static_assert(std::is_pointer<T>{} || std::is_same<T, std::nullptr_t>{},
"Not a pointer type!");
注意:C++14 还引入了 std::is_null_pointer
.
关于c++通过多个函数传递nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401214/