嗯......标题有点拗口,但我真的不确定这是哪一部分导致问题,我已经经历了很多次,并且无法确定原因......
这个想法是让单个 Choice 实例能够存储传递给它的模板列表的任何类型的任何一个值......它有点像一个联合,除了它跟踪被存储的类型并考虑值每种类型都是不同的,这允许它绕过联合成员中构造函数的 C++ 约束。
它在某些情况下确实有效,但清理代码似乎存在一些问题。当我开始使用这个结构和参数列表中传递的 std::basic_string 或类似类型时,我开始遇到段错误,但我不明白为什么会导致任何问题。
这对我自己来说是一种虽然实验,但我看不出它不应该工作的任何原因(在 g++ 中以 C++0x 模式编译):
// virtual methods should provide a way of "remembering"
// the type stored within the choice at any given time
struct ChoiceValue
{
virtual void del(void* value) = 0;
virtual bool is(int choice) = 0;
};
// Choices are initialized with an instance
// of this structure in their choice buffer
// which should handle the uninitialized case
struct DefaultChoiceValue : public IChoiceValue
{
virtual void del(void* value) {}
virtual bool is(int choice) { return false; }
};
// When a choice is actually initialized with a value
// an instance of this structure (with the appropriate value
// for T and TChoice) is created and stored in the choice
// buffer, allowing it to be cleaned up later (using del())
template<int TChoice, typename T>
struct ChoiceValue
{
virtual void del(void* value) { ((T*)value)->~T(); }
virtual bool is(int choice) { return choice == TChoice; }
};
template<typename ... TAll>
struct Choice
{
};
template<typename T1, typename ... TRest>
struct Choice<T1, TRest...>
{
// these two constants should compute the buffer size needed to store
// the largest possible value for the choice and the actual value
static const int CSize = sizeof(ChoiceValue<0, T1>) > Choice<TRest...>::CSize
? sizeof(ChoiceValue<0, T1>) : Choice<TRest...>::CSize;
static const int VSize = sizeof(T1) > Choice<TRest...>::VSize
? sizeof(T1) : Choice<TRest...>::VSize;
IChoiceValue* _choice;
char* _choiceBuffer;
char* _valueBuffer;
Choice()
{
_choiceBuffer = new char[CSize];
_valueBuffer = new char[VSize];
_choice = new (_choiceBuffer) DefaultChoiceValue();
}
~Choice()
{
_choice->del(_valueBuffer);
delete[] _choiceBuffer;
delete[] _valueBuffer;
}
template<int TChoice, typename T>
T& get()
{
if(_choice->is(TChoice))
return *(T*)_valueBuffer;
else
{
_choice->del(_valueBuffer);
new (_valueBuffer) T();
_choice = new (_choiceBuffer) ChoiceValue<TChoice, T>();
return *(T*)_valueBuffer;
}
}
};
template<typename T1>
struct Choice<T1>
{
// required for the base case of a template
// with one type argument
static const int CSize = sizeof(ChoiceValue<0, T1>) > sizeof(DefaultChoiceValue)
? sizeof(ChoiceValue<0, T1>) : sizeof(DefaultChoiceValue);
static const int VSize = sizeof(T1);
// I have an implementation here as well in my code
// but it is pretty much just a copy of the above code
// used in the multiple types case
};
非常感谢,如果有人能找出我做错了什么:)