gpt4 book ai didi

c++ - const 函数调用非 const 或反之亦然(避免重复)?

转载 作者:IT老高 更新时间:2023-10-28 23:10:04 24 4
gpt4 key购买 nike

使用一个比另一个有什么优势:

class Foo
{
public:
const int& get() const
{
// stuff here
return myInt;
}

int& get()
{
return const_cast<int&>(static_cast<const Foo*>(this)->get());
}
};

或者

class Foo
{
public:
int& get()
{
// stuff here
return myInt;
}

const int& get() const
{
return const_cast<Foo*>(this)->get();
}
};

我只使用了第一个,但我看到第二个在某个地方使用过,所以我想知道。

注释 //stuff here 可能是一项重要的检查,例如检索表的索引以返回表成员的引用(例如:myInt = myTable[myComputedIndex];) 所以我不能把它公开。因此 table 和任何成员都不是 const。

最佳答案

如果您必须创建一个与 const 无关并避免重复的函数,那么一种巧妙的方法是将实现委托(delegate)给模板,例如

class Foo {
private:

int my_int;
template <typename ThisPtr>
static auto& get(ThisPtr this_ptr) {
return this_ptr->my_int;
}

public:
int& get() {
return get(this);
}

const int& get() const {
return get(this);
}
};

这样你就不用担心在这种情况下使用 const_castmutable 和其他试图减少代码重复的东西。如果出现错误,编译器会通知您。

关于c++ - const 函数调用非 const 或反之亦然(避免重复)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755608/

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