标准 C++14 中零大小数组的解决方法?
Workaround for zero-sized arrays in standard C++14?
我正在为 Google 的 V8 ECMAScript 引擎开发绑定工具包。
考虑这个模板函数:
template<class... Types> void call_v8_function(v8::Local<v8::Function> function,
Types... args) {
...significant amount of context set-up here...
v8::Local<v8::Value> call_args[] = { V8Utils::to_js_value(isolate, args)... };
function->Call(this->context, sizeof...(args), call_args);
}
它接受可变数量的参数,并使用辅助函数将它们映射到 v8::Value 对象数组。 (参数可以有任意类型,只要它们被 to_js_value
识别)当我使用 GCC 或 Clang 编译时,这非常有效。
然而,在Visual Studio中,它完全崩溃了。当在没有任何附加参数的情况下调用此模板函数时,将声明一个大小为 0 的数组。虽然被 GCC 和 Clang 接受,但该标准不允许这样做,并且 Visual Studio 正确地吐出 error C2466: cannot allocate an array of constant size 0
.
因为我发现这种方法非常方便,所以我正在寻找一种方法让它工作,而不是为无参数情况复制函数,因为这会导致大量代码重复。
您可以使用 std::array
which already has a specialization for zero-sized arrays. Furthermore, for your function call the data()
member is also well-behaved 作为空数组,而不是 c 风格的数组。
我正在为 Google 的 V8 ECMAScript 引擎开发绑定工具包。 考虑这个模板函数:
template<class... Types> void call_v8_function(v8::Local<v8::Function> function,
Types... args) {
...significant amount of context set-up here...
v8::Local<v8::Value> call_args[] = { V8Utils::to_js_value(isolate, args)... };
function->Call(this->context, sizeof...(args), call_args);
}
它接受可变数量的参数,并使用辅助函数将它们映射到 v8::Value 对象数组。 (参数可以有任意类型,只要它们被 to_js_value
识别)当我使用 GCC 或 Clang 编译时,这非常有效。
然而,在Visual Studio中,它完全崩溃了。当在没有任何附加参数的情况下调用此模板函数时,将声明一个大小为 0 的数组。虽然被 GCC 和 Clang 接受,但该标准不允许这样做,并且 Visual Studio 正确地吐出 error C2466: cannot allocate an array of constant size 0
.
因为我发现这种方法非常方便,所以我正在寻找一种方法让它工作,而不是为无参数情况复制函数,因为这会导致大量代码重复。
您可以使用 std::array
which already has a specialization for zero-sized arrays. Furthermore, for your function call the data()
member is also well-behaved 作为空数组,而不是 c 风格的数组。