【问题标题】:How is luabind::object's assignment operator overloaded?luabind::object 的赋值运算符是如何重载的?
【发布时间】:2013-08-09 14:35:42
【问题描述】:

我正在学习 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。

并且在类声明中,赋值运算符被重载为任意类型,而不仅仅是object&:

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

object& operator=(object const&); 

对了,我发现我的问题类似于this,但是没有人回答。

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

谁能告诉我为什么第一个代码不正确以及operator=(T const &amp;) 是否超载?

非常感谢!!

【问题讨论】:

    标签: c++ lua operator-overloading luabind


    【解决方案1】:

    Luabind 0.9.1 在对象中没有这样的 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 实例化。

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 2013-03-30
      • 2013-02-14
      • 2016-08-30
      • 1970-01-01
      相关资源
      最近更新 更多