如何包装模板化函数来处理const和非const数据

the*_*ill 5 c++ const c++11

我想创建一个模板化函数,它对const和非const数据的工作方式相同,只是它会根据需要返回一个const或非const指针.

例如,我想返回一个指向容器中匹配元素的指针:

template <class Container, class Pred>
typename Container::value_type* getValuePtrIf(Container& c, Pred pred)
{
    auto it=std::find_if(c.begin(), c.end(), pred);
    return (it!=c.end()) ? &(*it) : nullptr;
}
Run Code Online (Sandbox Code Playgroud)

但是我无法为const和非const调用构建它.如果我省略了Container& c声明中的const 然后它不能返回一个const指针,但如果我改为const Container& c那么我可以返回一个const指针,但是然后非const的情况不会构建.

有没有一种方法来定义它,以便将其const解释为Container模板参数的一部分,以便我只需要定义此函数的一个版本?

Arn*_*rtz 6

从代码看,您的编译器似乎支持C++ 11.然后你可以使用decltype和尾随返回类型:

template <class Container, class Pred>
auto getValuePtrIf(Container& c, Pred pred) -> decltype(&*std::begin(c))
{
    auto it=std::find_if(std::begin(c), std::end(c), pred);
    return (it!=std::end(c)) ? &(*it) : nullptr;
}
Run Code Online (Sandbox Code Playgroud)

it将是任何类型std::begin(c)给你(iteratorconst_iterator),所以类型&(*it)是相同的decltype(&*std::begin(c)).