大佬教程收集整理的这篇文章主要介绍了将返回类型的函数参数的常量性与概念匹配,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
C++ 容器不包含 const 元素,例如你有const std::vector<int>
,而不是std::vector<const int>
。
当我尝试根据传递的容器是否为常量来调整函数的返回值类型时,这有点不幸。
这是一个励志的例子,请不要过多关注算法或boost的使用,我只使用它,因为C++ optional 不支持引用。
这段代码appears to work,但是代码看起来很丑,所以我想知道概念是否给了我们一种更好的方式来编写它。 我认为不是,因为基本上概念只是谓词,但我希望有一些好的东西,特别是返回类型非常垃圾。
template<typename C>
using match_const = std::conditional_t< std::is_const_v<std::remove_reference_t<C>>,const typename std::remove_reference_t<C>::value_type,typename std::remove_reference_t<C>::value_type>;
// no consTraints
auto ofind(auto& container,const auto& value) -> boost::optional<match_const<decltype(container)>&> {
if (auto it = std::ranges::find(container,value); it!=container.end()){
return *it;
}
return boost::none;
}
// dummy concept
template<typename C>
concept Container = requires (C C){
{C.begin()};
{C.end()};
{C.size()} -> std::same_as<size_t>;
};
// consTraints version
auto ofind2(Container auto& container,const auto& value) ->boost::optional<match_const<decltype(container)>&>{
if (auto it = std::ranges::find(container,value); it!=container.end()){
return *it;
}
return boost::none;
}
如果我的问题太模糊,这里是我理想化的版本:
boost::optional<Container::real_reference> ofind(Container auto& container,const auto& value)
其中 Container::real_reference 是与向量中的引用 typedef 不同的常量匹配的东西,例如考虑这个:
using CVI = const std::vector<int>;
static_assert(std::is_same_v<int&,CVI::reference>); // compiles
注意:我知道我应该让第二个参数也更受限制,但为了简单起见,我将其保留为 const auto&
。
Ranges 已经为我们提供了一种获取任何范围的正确引用类型的方法:
@H_674_37@std::ranges::range_reference_t<R>
如果 R
是 vector<int>
,那就是 int&
。如果 R
为 vector<int> const
,则为 int const&
。如果 R
是 span<int> const
,那仍然是 int&
,因为 span
是浅常量(这是你的 Trait 出错的地方,因为它假设一切都是深的——常量).
这个 Trait 并不神奇,它所做的只是为您提供底层迭代器取消引用的精确类型:decltype(*ranges::begin(r))
。
这样,您的 find
可能如下所示:
template <range R>
auto ofind(R& container,const auto& value) -> boost::optional<range_reference_t<R>>;
请注意,如果您确实需要使用参数的类型,由于必须编写 decltype
,因此使用缩写的函数模板语法实际上并不是全部缩写,因此你可以……使用普通的函数模板语法。
以上是大佬教程为你收集整理的将返回类型的函数参数的常量性与概念匹配全部内容,希望文章能够帮你解决将返回类型的函数参数的常量性与概念匹配所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。