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