c++通过多个函数传递nullptr

标签 c++ nullptr

我在处理某些代码时遇到问题,我需要在其中通过多层函数传递指针。指针可以为 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/

相关文章:

c++ - 为什么这里的三元运算符与 if-else 不同?

C++ 在尝试比较字符串 "=="或 CString.Find() 时什么更好

c++ - 重载 *= 用于复数

c++ - 如何修复此循环? C++

c++ - 返回空字符串文字 VS。返回 nullptr - 它们是否相同?

c++ - 从 nullptr 推导的指向模板类型?

c++ - 可以在 gcc 中模拟 nullptr 吗?

c++ - 关于从类里面获取值(value)的问题

c++ - std::thread - 命名你的线程

c++ - 我可以将 nullptr 存储到 bool 中吗?