luabind::对象的赋值运算符是如何重载的?

How is luabind::object's assignment operator overloaded?

本文关键字:重载 对象 赋值运算符 luabind 何重载      更新时间:2023-10-16

我正在学习luabind,并尝试使用luabind::object从C++访问Lua中的变量。

当我给一个"对象"分配一个int时,编译失败了。

守则:

int main()
{
    using namespace luabind;
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);
    open(L);
    luaL_dofile(L, "./test.lua"); // a = 5
    object g = globals(L);
    object num = g["a"];
    num = 6; // Failed to compile
    return 0;
}

错误消息:

luatets.cpp:21:6: error: no match for ‘operator=’ (operand types are ‘luabind::adl::object’ and ‘int’)
  num = 6;
/usr/include/luabind/object.hpp:731:9: note: luabind::adl::object& luabind::adl::object::operator=(const luabind::adl::object&)
   class object : public object_interface<object>
/usr/include/luabind/object.hpp:731:9: note:   no known conversion for argument 1 from ‘int’ to ‘const luabind::adl::object&’

但在我把这两行代码组合在一起后,代码就起作用了:

g["a"] = 6;

我不知道为什么会发生这种事。在luabind文档中,据说:

当您有一个Lua对象时,可以使用赋值运算符(=)为其指定一个新值。执行此操作时,default_policy将用于将C++值转换为Lua。

在类声明中,赋值运算符被重载用于任意类型,而不仅仅是对象&:

template <class T>
object& operator=(T const&);
object& operator=(object const&); 

顺便说一句,我发现我的问题和这个类似,但没有人回答

我看了一下luabind标头,但在那些可怕的代理中找不到任何线索。

有人能告诉我为什么第一个代码不正确,operator=(T const &)是否过载吗?

非常感谢!!

Luabind 0.9.1在对象中没有这样的运算符=重载,不管(可能已经过时了?!)文档怎么说。事实上,对象根本没有运算符=重载(也没有对象接口,对象是从中派生的)。

然而,它有:

template<class T>
    index_proxy<object> operator[](T const& key) const

这就是g["a"] = 6;工作的原因,因为index_proxy具有:

template<class T>
    this_type& operator=(T const& value)

可以为int.

实例化