gpt4 book ai didi

c++ - 如何避免这种重复

转载 作者:可可西里 更新时间:2023-11-01 15:51:51 25 4
gpt4 key购买 nike

我有类似的代码:

#include <string>

class A{
public:
std::string &get(){
return s;
}

const std::string &get() const{
return s;
}

std::string &get_def(std::string &def){
return ! s.empty() ? s : def;
}

// I know this might return temporary
const std::string &get_def(const std::string &def) const{
return ! s.empty() ? s : def;
}

private:
std::string s = "Hello";
};

我想知道是否有简单的方法来避免 get() 函数中的代码重复?

最佳答案

wandbox example

替代const_cast : 创建一个 static采用 *this 的模板函数作为引用:

class A
{
private:
template <typename TSelf, typename TStr>
static auto& get_def_impl(TSelf& self, TStr& def)
{
return !self.s.empty() ? self.s : def;
}

public:
auto& get_def(std::string& str)
{
return get_def_impl(*this, str);
}

const auto& get_def(const std::string& str) const
{
return get_def_impl(*this, str);
}
};

之所以有效,是因为 template argument deduction rules - 简而言之,TSelf将同时接受 const和非 const引用。

如果你需要访问this的成员里面get_def_impl , 使用 self.member .

此外,您可以使用 std::conditional或内部类似设施 get_def_impl根据 const 做不同的事情-性 TSelf .您还可以使用转发引用 ( TSelf&& ) 并处理 this 的情况由于ref-qualifiers而被移动和 perfect-forwarding .

关于c++ - 如何避免这种重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787837/

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