1

今天在调试 SWIG 类型映射时遇到了一个有趣的问题。有人愿意告诉我为什么 Visual C++ 2008 在从 转换为 时会抛出“转换丢失限定符”错误ourLib::Char *const ourLib::Char * &?我认为Type *->const Type *是一个微不足道的转换,并且(在调用函数时)Lvalue->Lvalue &也是如此。

编辑:我们最终采用的解决方案:

// ourLib::Char is a typedef'ed char on Win32

%typemap(in) const char* (const ourLib::Char* tmp)
{
    if (!bapiLua::LuaTraits<ourLib::Char*>::FromLuaObject(L, $argnum, tmp)) SWIG_fail;
    $1 = const_cast<char *>(tmp);
}

// And in a different source file, already written:
namespace bapiLua {
template<>
struct LuaTraits<ourLib::Char*>
{
    static ourLib::Bool FromLuaObject(lua_State* L, int pos, const ourLib::Char*& o_result);
};
}

删除constfromconst ourLib::Char * tmp会导致我描述的错误。

4

2 回答 2

9

假设您具有以下功能:

void test(  const char*& pRef)
{
    static const char somedata[] = { 'a' ,'b', 'c', '\0'};
    pRef = somedata;
}

如果你传入了一个非常量char*,那么当返回时,编译器将失去指向 istest()的事实。pconst

这与此 C++ FAQ Lite 问题中给出的原因基本相同(处理指向指针的指针而不是指针引用):

于 2009-08-10T21:16:19.080 回答
0

在以下代码中,

friend ostream & operator<<(ostream & output, const List& other)
{
    for(int i=0;i<other.length();i++)
        output << other.getData()[i] << " ";

    return output;
}

为了消除编译错误“Conversion lost qualifiers”,对于参数“const List& other”,我将以下两个调用方法都更改为 const。

T* getData() const
{
    return data;
}

int length() const
{
    return lSize;
}
于 2020-09-23T12:09:04.267 回答