gpt4 book ai didi

c++ - 仅将 const 引用绑定(bind)到 const 值

转载 作者:行者123 更新时间:2023-11-27 23:59:26 25 4
gpt4 key购买 nike

我正在编写一个代码,用于在集合的元素中查找对(使用特定条件)。我真的不想复制集合的元素,所以我想我会使用指针对。但是,如果原始集合中的值可以更改,这是不安全的。

在我的代码中,我想使用仅绑定(bind)到真正常量值的 const 引用(因为我不想让用户滥用这些对)。然而,这种方法:

using PairCollectionType =
std::vector<std::pair<std::shared_ptr<Cluster>, std::shared_ptr<Cluster>>>;

PairCollectionType getClusterPairCollection(
const std::vector<Cluster> const& clusterCollection)
{
// ...
}

-> 导致“重复的‘const’”错误。我知道这可以通过指针实现:

const ptr_type* const ptrThatBindsOnlyToConsts;

这是否也可以通过引用实现?

最佳答案

我不确定您需要这样做的理由。但是如果调用者传递一个非常量参数,你可以给出一个编译错误,通过添加重载来捕获这些情况:

void func(U const &)
{
// the real code
}

void func(U &) = delete;
void func(U&&) = delete;

int main()
{
U u;
U const cu {};

func(cu); // OK
func(u); // error
func(U{}); // error
}

关于c++ - 仅将 const 引用绑定(bind)到 const 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com