【发布时间】:2016-09-30 09:11:30
【问题描述】:
我有类似这样的代码:
#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 或什么都没有创建一个宏,但它不像 C++。
-
我什至没有办法重用没有 const_cast 的函数或使 s 可变
-
Ew @ 右对齐 & 符号 ;)
-
欺骗*.com/q/2150192/560648?虽然那个Q有点垃圾……
-
@LightnessRacesinOrbit - 正确答案在这里:*.com/questions/123758/…