我有一个具有成员方法f和g的类,都由const重载。有 在f()中调用g()。 f和const f的方法体是相同的。
class X {
void f() {/body ... g() /} const;
void f() {/body g() /};
void g() const;
void g();
};
由于f()和g()具有相同的方法体,我真的想要一个方法, 而不是在f和const f之间复制重复的代码。
此外,当为const对象执行f()的主体时,我想要明显的const g() 执行(非const对象的非const g())。
答案 0 :(得分:1)
我不相信这可以通过模板成员函数完成(但我可能很容易出错);所以最好的选择可能是将共享代码分解为另一种方法。
class X {
void g() const;
void g();
void body() const { ... }
void f() const { body(); g(); }
void f() { body(); g(); }
};
答案 1 :(得分:1)
从不同的角度来看,您不会有重复的代码,因为在g()
中调用的f()
不一样。你可以做的是分解f:
class X {
void body() {};
void f() {body(); g() } const;
void f() {body(); g() };
void g() const;
void g();
};
答案 2 :(得分:0)
你能做到这一点:
class X {
void body(){/body ... /} const;
void f() {body(); g(); } const;
void f() {body(); g(); };
void g() const;
void g();
};
如果你不能,是因为/ body ... /有const和非const版本吗?
如果是这样,即使它是相同的源,它也是一个不同的含义 - 它会以不同的方式编译,所以你不能共享源,除非你的意思是共享实际的代码行,而不是通过调用函数。
一些想法:
答案 3 :(得分:0)
class X {
void f_impl() const { /body }
void f() {f_impl(); ... g(); /} const;
void f() {f_impl(); g(); /};
void g() const;
void g();
};
答案 4 :(得分:0)
您可以在模板函数中实现f,该函数通过(X*)this
或(const X*)this
。
#include <cstdio>
class X {
void g() const { std::puts("const"); }
void g() { std::puts("non-const"); }
void body() const { }
public:
void f() const { f_impl(this); }
void f() { f_impl(this); }
private:
template <class Self>
static void f_impl(Self* self)
{
self->body();
self->g();
}
};
int main()
{
X x;
x.f();
const X y = {};
y.f();
}
(尽管如此,在头文件中实现大型函数可能并不是很好。)