Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何返回可选指针或引用(std::optional)?_C++_Templates_C++17_Stdoptional - Fatal编程技术网

C++ 如何返回可选指针或引用(std::optional)?

C++ 如何返回可选指针或引用(std::optional)?,c++,templates,c++17,stdoptional,C++,Templates,C++17,Stdoptional,假设我有以下模板函数: template <typename T> std::optional<std::reference_wrapper<const T>> larger(const T data[], size_t count) { if(!count) return std::nullopt; size_t index_max {}; for(size_t i {1ULL}; i < count; ++i)

假设我有以下模板函数:

template <typename T>
std::optional<std::reference_wrapper<const T>> larger(const T data[], size_t count) {
    if(!count) return std::nullopt;

    size_t index_max {};
    for(size_t i {1ULL}; i < count; ++i)
        index_max = data[i] > data[index_max] ? i : index_max;

    return std::optional< std::reference_wrapper<const T> > {&data[index_max]};
}
模板
标准::可选较大值(常数数据[],大小计数){
如果(!count)返回std::nullopt;
大小_t索引_max{};
对于(大小{1ULL};idata[index_max]?i:index_max;
返回std::optional{&data[index\u max]};
}
我试图做的是返回一个可选的引用,但没有成功。我不知道如何从这里开始。这就是我想到的,最初我使用的返回类型是
std::optional

您有一个“输入错误”,它应该是(没有
&
):

您有一个“输入错误”,它应该是(没有
&
):


@Nicolas不一定。例如,空数组。数据[0]将不是(不应该)要返回的有效引用。我做的更多的是C++技术练习,而不是思考情况的实用性。一个“可选”<代码> STD::RealthyOnWrpuls<代码>在逻辑上等价于一个指针。空指针?没有汤给你!非空指针?这是你的目标。结束。“你越想水管,就越容易堵住下水道”--斯科蒂,《星际迷航III》。为什么不直接返回
const T*
?如果它是
nullptr
,则没有数据。这是人们通常做的。@ Alx23 z这是一个C++技术问题,而不是寻找替代的(更好的)方法来解决这个问题。答案是:<代码> STD::可选的< /C> >是为了某个目的而设计的。您所问的不是
std::optional
的设计目的。原始指针用于此操作。最多考虑<代码> ObServRIPPTR < /代码>。@ NigoBuras不一定。例如,空数组。数据[0]将不是(不应该)要返回的有效引用。我做的更多的是C++技术练习,而不是思考情况的实用性。一个“可选”<代码> STD::RealthyOnWrpuls<代码>在逻辑上等价于一个指针。空指针?没有汤给你!非空指针?这是你的目标。结束。“你越想水管,就越容易堵住下水道”--斯科蒂,《星际迷航III》。为什么不直接返回
const T*
?如果它是
nullptr
,则没有数据。这是人们通常做的。@ Alx23 z这是一个C++技术问题,而不是寻找替代的(更好的)方法来解决这个问题。答案是:<代码> STD::可选的< /C> >是为了某个目的而设计的。您所问的不是
std::optional
的设计目的。原始指针用于此操作。最多考虑<代码> ObServyPPTR <代码>。我最初写的是返回语句,但仍然不起作用。事实证明,我没有包含
标题。我最初编写了return语句,但它仍然不起作用。事实证明,我没有包含
标题。
return std::optional< std::reference_wrapper<const T> > {data[index_max]};
return std::cref(data[index_max]);