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;
}
};
I want to clarify the fact - it is a part of the working code. You can do this in C++. I just want to do it in a more nice way.
I've found a way to get rid of unlock and try block. I've remembered there is such a thing as thread local storage. Now I can write constructor as simple as that:
TestRecordset(wstring param_value):
Recordset(open_database(L"test.db")), param("PARAM") {
param = param_value;
fetch();
}
to dribeas:
My objective is to avoid redundant and tedious typing. Without some tricks behind the scene I will have to type for each Field and Param:
TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param(this, "PARAM"),
field1(this, 0), field2(this, 1), field3(this, 2) { ... }
它是多余的、丑陋的和不方便的。例如,如果我必须在 SELECT 中间添加新字段,我将不得不重写所有列号。关于您的帖子的一些注释:
- 字段和参数由它们的默认构造函数初始化。
- 构造函数中初始化程序的顺序无关紧要。字段始终按照其声明的顺序进行初始化。我已经使用这个事实来追踪字段的列索引
- 首先构造基类。因此,当构造字段时,Recordset 中的内部字段列表已准备好由 Filed 默认构造函数使用。
- 我不能在这里使用 RAII。我需要在 Recorset 构造函数中获取锁,并在构造所有字段后在 TestRecordset 构造函数中强制释放它。