luabind::object的赋值运算符如何重载?

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

当我将 int 分配给一个“object”时,编译失败了。

代码:

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 foroperator=’ (operand types are ‘luabind::adl::object’ andint’)
  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 对象时,您可以使用赋值运算符(=)为其分配一个新值。 这样做时,将使用默认策略将 C++ 值转换为 Lua 值。

在类声明中,赋值运算符对任意类型进行了重载,不仅仅是对 object& 进行了重载:

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

object& operator=(object const&);

顺便说一下,我发现我的问题类似于这个,但没有人回答它。

我已经查看了 luabind 头文件,但在这些可怕的代理中找不到任何线索。

有谁能告诉我为什么第一段代码不正确,以及 operator=(T const&) 是否被重载?

非常感谢!!

点赞
用户3811101
用户3811101

Luabind 0.9.1 中的 object 并没有 operator= 重载,与文档中(可能已过时?!)所说的不同。实际上,object 没有任何 operator= 重载(object_interface 也是如此,它是从 object 派生而来的)。

不过,它有:

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。

2014-09-19 01:34:18