学网站建设怎么样,网站建设论文答辩自述,企业营销图片,html网页制作下载深入理解 C 中的 std::cref、std::ref 和 std::reference_wrapper 在 C 编程中#xff0c;有时候我们需要在不进行拷贝的情况下传递引用#xff0c;或者在需要引用的地方使用常量对象。为了解决这些问题#xff0c;C 标准库提供了三个有用的工具#xff1a;std::cref、std:… 深入理解 C 中的 std::cref、std::ref 和 std::reference_wrapper 在 C 编程中有时候我们需要在不进行拷贝的情况下传递引用或者在需要引用的地方使用常量对象。为了解决这些问题C 标准库提供了三个有用的工具std::cref、std::ref 和 std::reference_wrapper。这篇文章将深入探讨这些工具的用途、区别以及实际应用。 此外我们知道Rust语言中经常实现了Unwrap方法在C中如何实现 这就参考Apache arrow的代码了有这么一段 std::optionalstd::reference_wrapperconst TransportStatusDetail
TransportStatusDetail::Unwrap(const Status status) {std::shared_ptrStatusDetail detail status.detail();if (!detail) return std::nullopt;if (detail-type_id() ! kTypeId) return std::nullopt;return std::cref(arrow::internal::checked_castconst TransportStatusDetail(*detail));
} 随后我们便可以通过这样调用提取出Status中实际的TransportStatusDetail。 Status status(transportDetail);
auto result Unwrap(status); 下面来从几个方面看看最后给出整个Demo代码。 1. std::cref创建常量引用 std::cref 是一个模板函数用于创建对常量对象的引用。它返回一个 std::reference_wrapper 对象可以在需要引用的地方使用。这在函数参数传递中特别有用因为它允许我们在不进行拷贝的情况下传递常量对象同时保持引用的语义。 示例 #include iostream
#include functionalvoid printValue(const int value) {std::cout Value: value std::endl;
}int main() {int number 42;auto crefNumber std::cref(number);printValue(crefNumber); // 使用常量引用传递参数return 0;
} 2. std::ref创建可修改的引用 与 std::cref 不同std::ref 是一个模板函数用于创建对可修改对象的引用。它返回一个 std::reference_wrapper 对象允许我们在需要引用的地方使用同时允许修改被引用的对象。 示例 #include iostream
#include functionalvoid modifyValue(int value) {value * 2;
}int main() {int number 42;auto refNumber std::ref(number);modifyValue(refNumber); // 使用可修改的引用作为参数std::cout Modified Value: number std::endl;return 0;
} 3. std::reference_wrapper引用的包装器 std::reference_wrapper 是一个模板类用于包装引用使其能够在容器中存储或以引用的形式传递。它提供类似引用的语法并且可以与标准容器一起使用因为容器无法直接存储引用。 示例 #include iostream
#include vector
#include functionalint main() {int number1 42;int number2 73;std::vectorstd::reference_wrapperint numbers {std::ref(number1), std::ref(number2)};for (auto num : numbers) {num.get() 10; // 修改原始对象的值}std::cout Number 1: number1 std::endl;std::cout Number 2: number2 std::endl;return 0;
} 在这个示例中std::reference_wrapper 允许我们将引用包装在容器中然后通过 get() 方法来访问和修改原始对象的值。 4.Unwrap Demo 这里给出具体的代码段其完整代码参见知识星球内容。 std::optionalstd::reference_wrapperconst TransportStatusDetail Unwrap(const Status status) {std::shared_ptrStatusDetail detail status.detail();if (!detail) return std::nullopt;if (detail-type_id() ! kTypeId) return std::nullopt;return std::cref(static_castconst TransportStatusDetail(*detail));
}int main() {// 创建 TransportStatusDetail 对象std::shared_ptrStatusDetail transportDetail std::make_sharedTransportStatusDetail();// 创建 Status 对象并传入 TransportStatusDetail 对象Status status(transportDetail);auto result Unwrap(status);if (result) {const TransportStatusDetail detail result.value().get();// 使用 detail 进行操作std::cout TransportStatusDetail found. std::endl;} else {std::cout No valid TransportStatusDetail found. std::endl;}return 0;
} 欢迎一起探讨C那些事更多项目/内容欢迎加入知识星球。