2

我在处理一些代码时遇到问题,我需要通过多层函数传递指针。指针可以为空,因此对于 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以使其调用“正确”版本?

4

3 回答 3

5

你需要一个函数模板:

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*,无论它是从什么类型转换而来的。static_assert确保它T是指针类型也可能是有序的:

static_assert(std::is_pointer<T>{} || std::is_same<T, std::nullptr_t>{},
    "Not a pointer type!");

注意:C++14 还引入了std::is_null_pointer.

于 2014-12-10T12:42:05.370 回答
1

为什么不在函数nullptr的开头检查double*

在您的情况下,您不需要为nullptr_t. std::nullptr_t在这个问题中解释 了用法:`std::nullptr_t` 类型的用途是什么?

所以这对你来说意味着:如果你有另一个test_ptr函数,它接受一个指针类型,那么你需要一个重载的带有std::nullptr_t. 但是只有一个test_ptr功能,没有必要。

于 2014-12-10T12:47:27.110 回答
1

调用后test(nullptr)你有double*一个恰好为 null,但该值是一个运行时属性,它的静态类型是double*,所以test_ptr(d)总是会选择test_ptr(double*). 重载在编译时根据类型而不是运行时值选择函数。

于 2014-12-10T12:48:41.310 回答