我想创建一个模板化函数,它对 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;
}
但是,我无法为 const 和非常量调用构建它。如果我在声明中省略了 const,Container& c
那么它就不能返回一个 const 指针,但是如果我更改为,const Container& c
那么我可以返回一个 const 指针,但是非 const 情况不会建立。
有没有一种方法来定义它,以便将其const
解释为Container
模板参数的一部分,以便我只需要定义这个函数的一个版本?