class C {
public
T x;
};
有没有一种优雅的方式让x的构造函数知道暗含地它正在构造的C的实例中? 成员怎样才能知道它构造的类实例?
我已经用一些肮脏不雅的机器实现了这样的行为。我需要这个为我的sqlite3包装。我不喜欢我见过的所有包装,他们的API IMO丑陋和不方便。我想是这样的:
class TestRecordset: public Recordset {
public:
// The order of fields declarations specifies column index of the field.
// There is TestRecordset* pointer inside Field class,
// but it goes here indirectly so I don't have to
// re-type all the fields in the constructor initializer list.
Field<__int64> field1;
Field<wstring> field2;
Field<double> field3;
// have TestRecordset* pointer too so only name of parameter is specified
// in TestRecordset constructor
Param<wstring> param;
virtual string get_sql() {
return "SELECT 1, '1', NULL FROM test_table WHERE param=:PARAM";
}
// try & unlock are there because of my dirty tricks.
// I want to get rid of them.
TestRecordset(wstring param_value)
try : Recordset(open_database(L"test.db")), param("PARAM") {
param = param_value;
// I LOVE RAII but i cant use it here.
// Lock is set in Recordset constructor,
// not in TestRecordset constructor.
unlock(this);
fetch();
} catch(...) {
unlock(this);
throw;
}
};
我想澄清一个事实 - 它是工作代码的一部分。你在可以在C++中做到这一点。我只是想以更好的方式做到这一点。
我发现了一种摆脱解锁和尝试块的方法。我记得有线程本地存储这样的东西。现在,我可以写构造器那样简单:
TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param("PARAM") { param = param_value; fetch(); }
到dribeas: 我的目标是避免重复和繁琐的打字。如果没有幕后的一些技巧,我将不得不键入每个字段和帕拉姆:
TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param(this, "PARAM"), field1(this, 0), field2(this, 1), field3(this, 2) { ... }
这是多余的,难看又不方便。例如,如果我不得不在SELECT的中间添加新字段,我将不得不重写所有列号。 您的文章的一些注意事项:
- 领域,而params 是通过其默认的构造函数初始化。
- 构造函数中初始化符的顺序是不相关的。字段总是按其声明的顺序进行初始化。我用这个事实来追踪字段的列索引
- 基类是首先构造的。因此,当Fields被构建时,Recordset中的内部字段列表已准备好由Filed默认构造函数使用。
- 我不能在这里使用RAII。我需要在Recorset构造函数中获取锁定,并在构造完所有Fields后,在TestRecordset构造函数中释放它。。
我实际上写了一个答案,抱怨你在构造函数中缺少RAII,但之后当我注意到基类构造函数调用时删除了它。 – 2008-12-03 20:39:31
另一方面,在RecordSet构造函数中解锁也不是更好吗? – 2008-12-03 20:40:27
不需要。我需要在Recordset构造函数中使用qcquire锁,并在构造完所有Fileds和Params后,在TestRecordset构造函数中强制释放锁。 – 2008-12-04 09:29:01