【发布时间】:2013-09-23 17:47:04
【问题描述】:
我正在围绕 Lua 的 C Api 编写一个简单的包装器,并让函数接受 lua_State& 而不是指针。但是,当我尝试传递 lua_State* 值时,我必须取消引用它以通过引用传递。扩展为的模板具有 func sig,其中 vm 按值而不是引用传递。
由于可以在没有完整定义的情况下使用对象的引用和指针,有没有一种方法可以将指针值转换为只需要类型的前向声明的引用值?
编辑: 在玩了一些代码之后。取消引用适用于其中一个函数调用,但在另一个函数调用上失败。
namespace Vm {
template<typename VM, typename T>
void push( VM vm, T value );
// If this function isn't here, push will fail too.
template<typename T>
void push( lua_State& luaState, T value ) {
Vm::push( luaState, value );
}
template<>
void push( lua_State& luaState, double value ) {
lua_pushnumber( &luaState, value );
}
template<typename VM>
void pop( VM vm, Uint32 nIndices );
template<>
void pop( lua_State& luaState, Uint32 nIndices ) {
lua_pop( &luaState, nIndices );
}
}
int main( int argc, char** argv )
{
lua_State* luaState = luaL_newstate();
luaL_openlibs( luaState );
Vm::push( *luaState, (double)1.2f ); // This works fine.
Vm::pop( *luaState, 1 ); // This generates error.
}
编译器错误:
error: invalid use of incomplete type ‘struct lua_State’
error: forward declaration of ‘struct lua_State’
error: initializing argument 1 of ‘void Vm::pop(VM, Uint32) [with VM = lua_State; Uint32 = unsigned int]’
【问题讨论】:
-
你使用哪种演员阵容?
-
你描述的应该没问题;您不需要类型定义来取消引用指针并获取引用:ideone.com/yxrt94。你能发布一些给出错误的示例代码吗?
-
我正在寻找某种类型的演员,但我刚刚找到了 reinterpret_cast
() 这可能就是我正在寻找的。span> -
@syam:我们应该建议弃用
reinterpret_cast<...>()并用this_is_not_the_cast_you_are_looking_for<...>()替换它。 -
@DietmarKühl
i_take_full_responsibility_of_whatever_bug_ensues<...>()我认为更像是一种威慑。责任使人害怕。 ;)