我有类似的代码:
#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() 函数中的代码重复?
最佳答案
替代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/